Resize textField Based On Content

坚强是说给别人听的谎言 提交于 2019-11-27 02:01:18
Christian Wörz

You have to use an UITextView instead of an UITextField.

Then, you can use the sizeThatFits method.

But first you have to know how high one line will be. You can get that information by using lineHeight:

var amountOfLinesToBeShown: CGFloat = 6
var maxHeight: CGFloat = yourTextview.font.lineHeight * amountOfLinesToBeShown

After that, just call the sizeThatFits method inside your viewDidLoad method and set the maxHeight (line * 6) as your textview height:

yourTextview.sizeThatFits(CGSizeMake(yourTextview.frame.size.width, maxHeight))

Swift 3

var textView : UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    textView = UITextView()
    textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: textView.frame.size.height))
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!