我知道互聯網上有很多關於這個問題的信息,但我被卡住了。我有我需要自定義我的UITextFields
的應用程序。例如,我需要在編輯開始時更改邊框顏色,或者需要限制可以在不同文本字段中設置多少個字符。我還需要在幾個文本字段中的圖像,這些圖像必須在左側縮進。爲了做到這一點,我決定製作自定義的UITextField類(以繼承UITextField)。我從UITextField
(實現<UITextFieldDelegate>
)創建了新班級。在該課程中,我使用self.delegate = self
(這在互聯網上廣泛使用,人們說它正在工作),所以我可以在我的自定義類中實現shouldChangeCharactersInRange
或textFieldShouldBeginEditing
。我的問題是,在此配置中,我收到無限循環並重新啓動應用程序(請參閱my question)。這來自self.delegate = self
。我知道在某些情況下,我可以使用observer
,但在這種情況下,我可以在班級中執行shouldChangeCharactersInRange
嗎? 如果我不以這種方式實現我的課,並將我的文本字段委託給我的視圖控制器。我必須在我的視圖控制器類中實現所有這些方法,在我看來這是非常難看的解決方案。如何正確地在iOS中繼承UITextField?
所以我的問題是如何正確實現UITextField子類?
P.S.我想我是以錯誤的方式去做的,但我無法弄清楚哪一個是正確的。
編輯:
這裏是我的代碼:
MyCustomTextField.h
@interface MyCustomTextField : UITextField
@property (nonatomic) int maxSymbols;
@property (nonatomic) int leftIndent;
@end
MyCustomTextField.m
@interface MyCustomTextField() <UITextFieldDelegate>
@end
@implementation MyCustomTextField
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
self.delegate = self;
self.clipsToBounds = YES;
[self setLeftViewMode:UITextFieldViewModeAlways];
UIImageView *imageView1 = [[UIImageView alloc]
initWithFrame:CGRectMake(0, 0, 37, 20)];
imageView1.image = [UIImage imageNamed:@"otp_back"];
self.leftView = imageView1;
}
return self;
}
- (CGRect) leftViewRectForBounds:(CGRect)bounds {
CGRect textRect = [super leftViewRectForBounds:bounds];
textRect.origin.x = 5;
return textRect;
}
這種方法也用於檢查最大長度:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// Restrict number of symbols in text field to "maxSymbols"
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
return newLength <= (int)_maxSymbols || returnKey;
}
當我去到文本字段,並開始從我收到的無限循環和退出與錯誤訪問模擬器的虛擬鍵盤輸入。這很奇怪,因爲如果鍵盤是數字或密碼類型,或者如果我從Mac鍵盤輸入,我沒有收到問題。
你能表現出一些實際的代碼?很多事情取決於你什麼時候說什麼。 – matt 2014-09-23 15:10:48