我找不到我的问题的解决方案,因为stackOverflow上的所有其他帖子都引用了使用 IDE 而不是以编程方式创建的 UITextField。
我UITextField
在里面创建 了一个自定义(void)viewDidLoad
。我以编程方式创建了这个,所以我可以访问该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;
}
但我意识到我的 textField 没有“看到”上述功能。尝试过
[textField addTarget:self action:@selector(...
但没有运气。有什么帮助吗?