iOS UITextView和UITextField使用

释放双眼,带上耳机,听听看~!

UITextView

一、使用textView时,禁止弹出键盘的方法
1.设置self.textView.editable = NO;
注:xib中的textView,也可在xib的右边的Behavior中取消选中的Editable
2.实现代理方法

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
[textView resignFirstResponder];
return NO;
}

UITextField


1.限制输入,只需要输入数字的几种方法总结

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == self.textField){
NSUInteger lengthOfString = string.length;
for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {//只允许数字输入
unichar character = [string characterAtIndex:loopIndex];
if (character < 48) return NO; // 48 unichar for 0
if (character > 57) return NO; // 57 unichar for 9
}
}
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
int i = 0;
while (i < string.length) {
NSString *newString = [string substringWithRange:NSMakeRange(i, 1)];
NSRange range = [newString rangeOfCharacterFromSet:tmpSet];
if (range.length == 0) {
return  NO;
break;
}
i++;
}
if (textField.text.length == 0 && [string isEqualToString:@"0"]) {
return NO;
}
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (result.length == 0) return YES;
NSString *regex = @"^[1-9][0-9]*$";
NSPredicate *prd = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [prd evaluateWithObject:result];
}

人已赞赏
iOS文章

iOS不常用方法总结(获取某个view所在的控制器,禁止锁屏,iOS跳转到App Store下载应用评分等)

2020-2-20 16:29:46

iOS文章

iOS new与alloc/init的区别

2020-2-20 16:44:19

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索