1. 程式人生 > >iOS UITextField輸入框特殊限制

iOS UITextField輸入框特殊限制

1.帶有小數點的數字輸入框限制

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    CGFloat maxNumber = 6666.66;
    NSString *validStr = nil;
    NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
    if (NSNotFound == nDotLoc && 0
!= range.location) { validStr = @"0123456789.\n"; } else { validStr = @"0123456789\n"; } NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:validStr] invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""
]; if (![string isEqualToString:filtered]) { return NO; } if (NSNotFound != nDotLoc && range.location > nDotLoc + 2) { return NO; } NSString *num = [NSString stringWithFormat:@"%@%@",textField.text,string]; if (num.floatValue > maxNumber) { if
(![string isEqualToString:@""]) { return NO; } } return YES; }

2.處理鍵盤上方聯想輸入

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:inputTextField];


- (void)textFiledEditChanged:(NSNotification *)obj {

    //限制條件
    NSInteger length = 10;
    UITextField *textField = (UITextField *)obj.object;
    NSString *language = [[UIApplication sharedApplication]textInputMode].primaryLanguage;
    if ([language isEqualToString:@"zh-Hans"]) {

        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        if (!position) {

            if (textField.text.length > length) {

                textField.text = [textField.text substringToIndex:length];
            }
        }
    } else {

        if (textField.text.length > length) {

            textField.text = [textField.text substringToIndex:length];
        }
    }
}