headkit
headkit

Reputation: 3327

How to automatically adjust the width of a centered UITextfield in Swift while editing?

I have a custom UITextfield that is x-centered to its superview via a constraint. It also has a height-constraint and a nice thin line right under the text that has the same width as the textfield itself (like I said: custom). I now want to keep the UITextfield centered while editing its content, adjusting itself in width to its string content.

What right now happens is that it keeps its width while editing, cropping its overlapping content.

My code is kind of

// 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!

Upvotes: 0

Views: 143

Answers (1)

Japes
Japes

Reputation: 433

You have to use UITextView instead of UITextField and apply its sizeThatFits method (see this response)

Upvotes: 1

Related Questions