如何在Swift编辑时自动调整居中UITextfield的宽度



我有一个自定义UITextfield,它通过约束以x为中心。它也有一个高度约束和一个很好的细线的文本下,有相同的宽度作为文本字段本身(就像我说的:自定义)。现在我想在编辑内容时保持UITextfield居中,根据字符串内容调整宽度。

现在的情况是,它在编辑时保持其宽度,裁剪重叠的内容。

我的代码有点像

// on textfields editing change event
@IBAction func nameFieldEditingChanged(sender: AnyObject) {
    // set width of textfield to width of textstring
    checkUserNameTextfieldWidth()
}
func checkUserNameTextfieldWidth(){
    println("checkUserNameTextfieldWidth (userName.text) / (userName.frame.size.width) / (view.bounds.width)")
    // something has to happen here I guess...
}

非常感谢!

您必须使用UITextView而不是UITextField并应用其sizeThatFits方法(参见此响应)

最新更新