我正在開發一個阿拉伯語的應用程序,我有UITextField與textAlignment的權利。現在我想在左側顯示textField的清除按鈕。是否可以在不添加自定義按鈕的情況下執行此操作?如何在UITextField的左側顯示清除按鈕?
當前位置
所需位置
我正在開發一個阿拉伯語的應用程序,我有UITextField與textAlignment的權利。現在我想在左側顯示textField的清除按鈕。是否可以在不添加自定義按鈕的情況下執行此操作?如何在UITextField的左側顯示清除按鈕?
當前位置
所需位置
使用下面的類別,並確保你的文本對齊方式應該是正確的:)
@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
雖然我會建議檢查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)
}
}
輸出將是:
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)
}
}
希望工程