For 2018
It is one of the silliest bugs in iOS.
The class UITextViewFixed
is a usually a reasonable solution.
Here is the class:
@IBDesignable class UITextViewFixed: UITextView {
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
func setup() {
textContainerInset = UIEdgeInsets.zero
textContainer.lineFragmentPadding = 0
}
}
Don't forget to turn off scrollEnabled in the Inspector!
The solution does work properly in storyboard
The solution does work properly at runtime
That's it, you're done.
In general, that should be all you need in most cases.
Even if you are changing the height of the text view on the fly this usually does all you need.
(A common example of changing the height on the fly, is changing it as the user types.)
Here is the broken UITextView from Apple...
Here is UITextViewFixed
:
Note that of course you must
turn off scrollEnabled in the Inspector!
Don't forget to turn off scrollEnabled! :)
Some further issues
(1) In some unusual cases - example, some cases of flexible cell height table views with dynamically changing height - Apple does the most infuriating thing in the world: they add extra space at the bottom.
No, really! This would have to be one of the most infuriating things in iOS.
Here is a "quick fix" to add which often helps with that madness.
...
textContainerInset = UIEdgeInsets.zero
textContainer.lineFragmentPadding = 0
// this is not ideal, but you can sometimes use this
// to fix the "space at bottom" insanity
var b = bounds
let h = sizeThatFits(CGSize(
width: bounds.size.width,
height: CGFloat.greatestFiniteMagnitude)
).height
b.size.height = h
bounds = b
...
(2) Sometimes, to fix yet another subtle Apple mess-up, you have to add this:
override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
super.setContentOffset(contentOffset, animated: false)
}
(3) Arguably, we should be adding :
contentInset = UIEdgeInsets.zero
just after .lineFragmentPadding = 0
in UITextViewFixed
. However ... it just doesn't work in current iOS! It may be necessary to add that in the future.
The fact that UITextView
is totally broken in iOS is one of the weirdest things in all of mobile computing.
Finally, here's a somewhat similar tip for TextField: https://stackoverflow.com/a/43099816/294884