Resize textField Based On Content

后端 未结 3 902
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 10:37

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 co

相关标签:
3条回答
  • 2020-11-29 10:50

    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))
    }
    
    0 讨论(0)
  • 2020-11-29 10:56

    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))
    
    0 讨论(0)
  • 2020-11-29 11:02

    Swift 5

    Simpler way:

    textField.text = "hola"
    textField.frame.size.width = textField.intrinsicContentSize.width
    
    0 讨论(0)
提交回复
热议问题