我找不到解決方案,因爲所有其他帖子stackOverflow都是指用IDE創建的UITextField,而不是編程方式。設置自定義UITextField最大長度
我在(void)viewDidLoad
內部創建了一個自定義UITextField
。我以編程方式創建了此項,因此我可以訪問leftView
屬性。
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 66, screenAdj, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font=[UIFont fontWithName:@"Helvetica" size:14];
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
[textField addTarget:self action:@selector(textFieldShouldReturn:)forControlEvents:UIControlEventEditingDidEndOnExit];
textField.text=[defaults stringForKey:@"username"];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
label.font=[UIFont fontWithName:@"Helvetica" size:14];
label.text = @"Your name";
label.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
textField.leftViewMode = UITextFieldViewModeAlways;
textField.leftView = label;
我也想限制TextField內的最大字符實現:
- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
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 <= MAX_LENGTH_USERNAME || returnKey;
}
但我意識到,我的文本框沒有 「發現」 上面function.Tried與
[textField addTarget:self action:@selector(...
但沒有運氣。 有什麼幫助嗎?
爲什麼你最重要的一段代碼呢? [tff addTarget:self action:@selector(changed :) forControlEvents:UIControlEventEditingChanged];是你需要的東西。 – jimpic
嘗試textField.delegate = self;並且viewcontroller實現了shouldChangeCharactersInRange; – zt9788
Jimpic它沒有工作。但我得到了我的解決方案,無論如何。 – Theodoros80