Resize textField Based On Content

不问归期 提交于 2019-11-26 09:55:11

问题


How can a textField be resized based on content while using auto-layout in an iOS application written in Swift?

The text field will resize as necessary to fit its content when the view loads as well as while the user is typing.

Ideally, the text field would stop resizing at a certain point, say, 6 lines, and become scrollable.


回答1:


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))



回答2:


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))
}


来源:https://stackoverflow.com/questions/28389913/resize-textfield-based-on-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!