简体   繁体   English

动态更改UITextField宽度取决于内容

[英]Change UITextField width dynamically depends of content

I have the same issue as here: Resize a UITextField while typing (by using Autolayout) 我和这里有同样的问题: 键入时调整UITextField的大小(通过使用Autolayout)

But It was resolved with UITextView and not with UITextField . 但这是通过UITextView而不是UITextField解决的。

This code doesn't help: 此代码无济于事:

func textFieldDidChange(sender: UITextField) {
    sender.invalidateIntrinsicContentSize()
}

I have UITextField (red background) and use AutoLayout with StackView: 我有UITextField (红色背景),并将AutoLayout与StackView一起使用:

在此处输入图片说明

and constraints: 和约束:

在此处输入图片说明

but UITextField change it width only when it is resignFirstResponder . 但是UITextField仅当它是resignFirstResponder时才更改其宽度。 Could you give me please any advice about the issue? 您能给我有关该问题的任何建议吗? I'm new in Swift and iOS Development. 我是Swift和iOS开发的新手。

UITextField does not call your method textFieldDidChange(_:) when it changes content (it is not part of UITextFieldDelegate ). UITextField更改内容时不调用方法textFieldDidChange(_:) (它不属于UITextFieldDelegate )。 You should use textField(_:shouldChangeCharactersInRange:replacementString:) instead. 您应该改用textField(_:shouldChangeCharactersInRange:replacementString:)

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    textField.invalidateIntrinsicContentSize()
    return true
}

To do this using Autolayout, you will need a constraint for the width of the text field. 要使用自动版式进行此操作,您将需要对文本字段的宽度进行约束。 Then, when the text changes, calculate the desired width and set the constant property on the constraint to that value. 然后,当文本更改时,计算所需的宽度并将约束上的constant属性设置为该值。 Lastly, you will need to call layoutIfNeeded() on the parent view. 最后,您需要在父视图上调用layoutIfNeeded()

This works for UITextField. 这适用于UITextField。 In my case I wanted the font to be of the same size. 就我而言,我希望字体大小相同。 I set textField width constraint to >= 10 and it just works fine on iOS 9, 10, 11. 我将textField宽度约束设置为> = 10,并且在iOS 9、10、11上正常运行。

For iOS 11 this even works while editing text. 对于iOS 11,甚至在编辑文本时也可以使用。

To make this work while editing text on iOS 9 and 10, I handled one more method by registering for a textDidChange event. 为了在iOS 9和10上编辑文本时使此工作有效,我通过注册textDidChange事件处理了另一种方法。

//Swift 3 Sample

//In viewDidLoad
adjustableTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)


 @objc func textFieldDidChange(_ textField: UITextField) {
    adjustableTextField.resignFirstResponder()
    adjustableTextField.becomeFirstResponder()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM