1.UITextField的光标太靠近边框
设置leftView 使光标和左侧边框的距离变大
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 30, [UIScreen mainScreen].bounds.size.width - 200, 30)];
[textField setBackgroundColor:[UIColor lightGrayColor]];
//******************
CGRect rect = textField.frame;
rect.size.width = 10;
UIView *view = [[UIView alloc]initWithFrame:rect];
textField.leftViewMode = UITextFieldViewModeAlways;
textField.leftView = view;
textField.delegate = self;
//******************
[self.view addSubview:textField];
2.监听return键点击
使用UITextField的代理UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([@"\n" isEqualToString:string] == YES) {
return NO;
}
return YES;
}
当string是'\n'的时候可以处理retur键n的操作。
3.控制UITextField输入字符的长度,可以使用上面的方法,监听每次字符变化,从而控制字符的输入个数
比如输入的长度为8的时候:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string length] > 0 && [textField.text length] >= 8)
{
return NO;
}
return YES;
}
4.其他的常用方法
//圆角
textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES;
//边框
textField.layer.borderColor=[[UIColor redColor]CGColor];
textField.layer.borderWidth= 1.0f;
//密码
textField.secureTextEntry = YES;