2

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
galenom
  • 89
  • 8

2 Answers2

2

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I haven't had a need to override UITextField before, so this is speculation, but couldn't you also override the text field's `textRectForBounds` method? – Duncan C Sep 10 '16 at 23:17
  • @DuncanC Uh, that's what I said. Only I said it in Swift 3. :) Xcode 8 has gone GM, time to step forward into the future. – matt Sep 10 '16 at 23:35
  • Close! but you definitely pointed me in the right direction. I already had the text field subclass so I looked into some of the other functions available. I needed the `editingRectForBounds(bounds:)`. Found my answer here: http://stackoverflow.com/questions/25367502/create-space-at-the-beginning-of-a-uitextfield – galenom Sep 13 '16 at 19:15
2

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

10623169
  • 984
  • 1
  • 12
  • 22
galenom
  • 89
  • 8