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

时间:2015-09-30 15:21:35

标签: swift xcode6 uitextfield

我有一个自定义的UITextfield,它通过约束以超级视图为中心。它还有一个高度约束和一条很好的细线,正好在文本下面,与文本字段本身具有相同的宽度(就像我说的:自定义)。 我现在想要在编辑其内容时保持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...

}

日Thnx!

1 个答案:

答案 0 :(得分:1)

您必须使用UITextView而不是UITextField并应用其sizeThatFits方法(请参阅this response