How to display the clear button on the left side of a UITextField?

I am developing an application in Arabic and I have a UITextField with a textAlignment rule. Now I want to show the clear text box button on the left. Can this be done without adding a custom button?

current position

clear button position

Desired position

clear button position

+6
source share
3 answers

Use the category below and make sure the text alignment should be correct :)

@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
+7
source

, userar answer, Swift 3 :

UITextField :

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)
    }
}

:

enter image description here

+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

0
source

Source: https://habr.com/ru/post/1017127/


All Articles