galenom
galenom

Reputation: 89

Swift - Disable text shifting when clear button appears

I have a UITextField in my project with the clear button enabled during editing.

Any centered text inside the box will shift to the left to make room for the clear button on focus. Is it possible for me to disable this shifting. I feel that it is distracting.

Please see the screenshots below: enter image description here enter image description here

Upvotes: 2

Views: 319

Answers (2)

galenom
galenom

Reputation: 89

To fix the issue I subclassed UITextField, and added the following to the subclass:

class CustomTextField: UITextField {
    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        return UIEdgeInsetsInsetRect(bounds, padding)
    }
}

Swift 4.2 & Xcode 10

class CustomTextField: UITextField {
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        return bounds.inset(by: padding)
    }
}

Answer was found here: Create space at the beginning of a UITextField

Upvotes: 2

matt
matt

Reputation: 535140

Is it possible for me to disable this shifting

With some care, yes, you can certainly do it. The drawing of the text is actually up to you, if you subclass UITextField: you can override drawText(in:) and/or textRect(forBounds:) and take charge of where the text goes.

Upvotes: 2

Related Questions