How do I size a UITextView to its content?
This works for both iOS 6.1 and iOS 7:
- (void)textViewDidChange:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
}
Or in Swift (Works with Swift 4.1 in iOS 11)
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
If you want support for iOS 6.1 then you should also:
textview.scrollEnabled = NO;
how to make UITextView height dynamic according to text length?
this Works for me, all other solutions didn't.
func adjustUITextViewHeight(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.scrollEnabled = false
}
In Swift 4 the syntax of arg.scrollEnabled = false
has changed to arg.isScrollEnabled = false
.
Dynamically adjust the height of the UITextView depending on its content?
Setup your constraints so that the edges are pinned but allow the text view to grow vertically. Then set a height constraint (the value doesn't matter here). Create an @IBOutlet
for the UITextView
and the height constraint. Then we can dynamically change the height in code:
class ViewControler: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.textView.delegate = self
}
func textViewDidChange(textView: UITextView) {
let sizeToFitIn = CGSizeMake(self.textView.bounds.size.width, CGFloat(MAXFLOAT))
let newSize = self.textView.sizeThatFits(sizeToFitIn)
self.textViewHeight.constant = newSize.height
}
}
Related Topics
How to Make App Wait Until Firebase Request Is Finished
How to Download and View Images from the New Firebase Storage
Convert Uiview to .Png in Swift
Get Section Number in Custom Cell Button Action
Uicollectionviewcontroller Error in Swift 3.0: Must Be Initialized with a Non-Nil Layout Parameter
Xcode 6 Ignoring Breakpoints - Swift
How to Instantiate and Load a View Controller Before Segueing to It Using Swift
How to Get Only Keys from Firebase
Empty Return Value from Swift Function Containing Closure
Swift - Uitableview Didselectrowatindexpath & Diddeselectrowatindexpath Add & Remove Indexpath Ids
How to Catch Nsunknownkeyexception in Swift 2.2
Sirikit, How to Display Response for Start Workout Intent
Tableview with Searchcontroller - Deinit Not Called
Swift and Nsuserdefaults - Exc_Bad_Instruction When User Defaults Empty