当先锋百科网

首页 1 2 3 4 5 6 7

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 = ; loopIndex < lengthOfString; loopIndex++) {//只允许数字输入
            unichar character = [string characterAtIndex:loopIndex];
            if (character < ) return NO; // 48 unichar for 0
            if (character > ) 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 = ;
    while (i < string.length) {
        NSString *newString = [string substringWithRange:NSMakeRange(i, )];
        NSRange range = [newString rangeOfCharacterFromSet:tmpSet];
        if (range.length == ) {
            return  NO;
            break;
        }
        i++;
    }
    if (textField.text.length ==  && [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 == ) return YES;
    NSString *regex = @"^[1-9][0-9]*$";
    NSPredicate *prd = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [prd evaluateWithObject:result];
}