一,UITextFild限制字数(三步)
1,给textfild添加响应事件,类型为:UIControlEventEditingChanged
[self.nickNameFild addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
2,实现上面的响应方法
- (void)textFieldDidChange:(UITextField *)textField{ if (textField.text.length > 20) { textField.text = [textField.text substringToIndex:20]; } }
3,实现textfild的代理方法
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ //只能输入20字的第一步 NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; if (toBeString.length > 20){ return NO; } return YES; }
小结:说是三步其实 也没多少代码…
二,TextView限制字数
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if (range.location>=300) { //此处提示字数超限 returnNO; } else { return YES; } }