blerch
blerch

Reputation: 395

UITextField's width is never less than it's width with placeholder text

I have a UITextField and UILabel sitting together in a UIView as so:

hand-drawn rendition of the layout

and here it is in Xcode:

screenshot of layout in Xcode

The label is hidden until the user enters some text into the text field, so it serves to provide a persistent "suffix" to the numeric entry. The problem is that when the user types a number into the text field, it doesn't shrink down to the size of the text, it remains at the size of the original placeholder, even though it isn't visible, as so:

screenshot of the problem

Is there any way I can constrain the text field's width to be the minimum size to accommodate the user's text, and not pay attention to the invisible placeholder text's width?

Thank you

Upvotes: 4

Views: 736

Answers (1)

blerch
blerch

Reputation: 395

I managed to solve it myself:

Whenever the text is edited, the text field is checked to see if there is any text inside. If there is no text, the 'mg' suffix is hidden, and the placeholder is added. If there is text, the 'mg' suffix is shown and the placeholder is removed. Like so: (Swift)

func textFieldTextChanged(_ textField: UITextField) {

    milligramTextField.invalidateIntrinsicContentSize()

    view.layoutIfNeeded()

    if textField.text == "" {
        milligramSuffixLabel.text = ""
        milligramTextField.placeholder = "0 mg"
    } else {
        milligramSuffixLabel.text = " mg"
        milligramTextField.placeholder = ""
    }
}

This answer was of great help.

Upvotes: 2

Related Questions