As you can see in this image
the UITextView
changes it\'s height according to the text length, I want to make it adjust it\'s height according to the te
Here are two pitfalls in iOS 8.3 when coming with textView.textContainer.maximumNumberOfLines = 10
Refer to my gist, please.
textView.attributedText = originalContent
let lineLimit = 10
textView.isEditable = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero // default is (8, 0, 8, 0)
textView.textContainer.maximumNumberOfLines = lineLimit // Important condition
textView.textContainer.lineBreakMode = .byTruncatingTail
// two incomplete methods, which do NOT work in iOS 8.3
// size.width可能比maxSize.width小 ————遗憾的是 iOS 8.3 上此方法无视maximumNumberOfLines参数,所以得借助于UILabel
// size.width may be less than maxSize.width, ---- Do NOT work in iOS 8.3, which disregards textView.textContainer.maximumNumberOfLines
// let size = textView.sizeThatFits(maxSize)
// 遗憾的是 iOS 8.3 上此方法失效了,得借助于UILabel
// Does not work in iOS 8.3
// let size = textView.layoutManager.usedRectForTextContainer(textView.textContainer).size
// Suggested method: use a temperary label to get its size
let label = UILabel(); label.attributedText = originalContent
let size = label.textRect(forBounds: CGRect(origin: .zero, size: maxSize), limitedToNumberOfLines: lineLimit).size
textView.frame.size = size
1 Add an observer to the content length of textfield
yourTextView.addObserver(self, forKeyPath: "contentSize", options: (NSKeyValueObservingOptions.new), context: nil);
2 Implement observer
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let tv = object as! UITextView;
var topCorrect = (tv.bounds.size.height - tv.contentSize.height * tv.zoomScale)/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset.x = 0;
tv.contentOffset.y = -topCorrect;
self.yourTextView.contentSize.height = tv.contentSize.height;
UIView.animate(withDuration: 0.2, animations: {
self.view.layoutIfNeeded();
});
}
In Storyboard / Interface Builder simply disable scrolling in the Attribute inspector.
In code textField.scrollEnabled = false
should do the trick.