2017-05-10 48 views

回答

7

使用下面的類別,並確保你的文本對齊方式應該是正確的:)

@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 
2

雖然我會建議檢查this answer處理左到右應用程序的語言,作爲一種解決方法,你可以遵循userar's answer,下面的代碼片段是一個斯威夫特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

0

SWIFT 3語法:

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

}

希望工程

相關問題