9

I'm developing an app in Arabic language and I have UITextField with textAlignment right. Now I want to show the clear button of the textField in left side. Is it possible to do this without adding a custom button?

Current position

clear button position

Desired position

clear button position

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Aruldevi R
  • 93
  • 4

3 Answers3

9

Use below category and make sure your text alignment should be right :)

@interface UICrossButtonTextField:UITextField
- (CGRect)clearButtonRectForBounds:(CGRect)bounds;
@end

@implementation UICrossButtonTextField
- (CGRect)clearButtonRectForBounds:(CGRect)bounds {
    CGRect originalRect = [super clearButtonRectForBounds:bounds];
    return CGRectOffset(originalRect, -originalRect.origin.x+5, 0); }


- (CGRect)editingRectForBounds:(CGRect)bounds {
    CGRect originalRect = [super clearButtonRectForBounds:bounds];
    bounds = CGRectMake(originalRect.size.width, bounds.origin.y, bounds.size.width-originalRect.size.width, bounds.size.height);
    return CGRectInset(bounds, 13, 3);
}

@end
Arun
  • 2,271
  • 1
  • 14
  • 18
3

Although I would recommend to check this answer for handling Left-to-Right App languages, as a workaround you could follow userar's answer, the following code snippet is a Swift 3 version of his answer:

Create a custom UITextField class, as follows:

class CustomTextField: UITextField {
    private var originalRect = CGRect.zero

    override func awakeFromNib() {
        super.awakeFromNib()

        originalRect = super.clearButtonRect(forBounds: bounds)
        clearButtonMode = .whileEditing
        textAlignment = .right
    }

    override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
        return originalRect.offsetBy(dx: -originalRect.origin.x + 5, dy: 0)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        let bounds = CGRect(x: originalRect.size.width, y: bounds.origin.y, width: bounds.size.width-originalRect.size.width, height: bounds.size.height)
        return bounds.insetBy(dx: 13, dy: 3)
    }
}

The output would be:

enter image description here

Community
  • 1
  • 1
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
2

SWIFT 3 syntax:

 class TextFields: UITextField {

  // You will need this
private var firstPlace = CGRect.zero

override func awakeFromNib() {
    super.awakeFromNib()

    firstPlace = super.clearButtonRect(forBounds: bounds) // to access clear button properties

/* uncomment these following lines if you want but you can change them in main.storyboard too 

    clearButtonMode = .whileEditing // to show the clear button only when typing starts

    textAlignment = .right // to put the text to right side
*/
}
   // Function to change the clear button
override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {

    return firstPlace.offsetBy(dx: -firstPlace.origin.x + 5, dy: 0)
}

}

hope it works

Atrin Noori
  • 311
  • 3
  • 12