How to increase width of textfield according to typed text?

前端 未结 8 1922
失恋的感觉
失恋的感觉 2020-12-09 04:22

I need to increase a text field\'s width according to its content. When the user inputs text, then the textfield size should increase automatically. I have one close (X) but

8条回答
  •  悲&欢浪女
    2020-12-09 04:57

    Implement following method of UITextFieldDelegate. Use approach provided by Matt to get required width of textField. In auto layout make sure you have centre and width constraints set for textfield. Create IBOutlet for your width constraint in code file. Also make sure you set delegate property of your textField

    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         let width = getWidth(text : textField.text)
         if width > widthConstraint.constant {
             widthConstraint.constant = width
         }
         self.layoutIfNeeded() 
         return true
    }
    

提交回复
热议问题