首先创建txtField
- 给txtField添加监听key值UIControlEventEditingChanged,当每输入一个字符的时候都会调用方法
txtEditing:
-(void)setTxt{
UITextField * txtFiled = [UITextField new]
self.txtField = txtFiled
txtFiled.layer.borderWidth = 2
txtFiled.layer.borderColor = [UIColor blackColor].CGColor
txtFiled.frame = CGRectMake(100, 100, 200, 40)
[txtFiled addTarget:self action:@selector(txtEditing:) forControlEvents:UIControlEventEditingChanged]
[self.view addSubview:txtFiled]
}
在输入触发方法中判断长度是否符合,并截取需要的长度,以及提示用户
-(void)txtEditing:(UITextField *)txtField{
NSLog(@"%@",txtField.text);
NSString * content = txtField.text;
if (content.length >= 5) {
UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:@"操作提示" message:@"长度超出" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
[alertVc addAction:action];
[self presentViewController:alertVc animated:YES completion:nil];
self.txtField.text = [self.txtField.text substringToIndex:4];
}
}