Set the maximum character length of a UITextField

前端 未结 30 1688
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

30条回答
  •  悲哀的现实
    2020-11-22 02:55

    The following code is similar to sickp's answer but handles correctly copy-paste operations. If you try to paste a text that is longer than the limit, the following code will truncate the text to fit the limit instead of refusing the paste operation completely.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        static const NSUInteger limit = 70; // we limit to 70 characters
        NSUInteger allowedLength = limit - [textField.text length] + range.length;
        if (string.length > allowedLength) {
            if (string.length > 1) {
                // get at least the part of the new string that fits
                NSString *limitedString = [string substringToIndex:allowedLength];
                NSMutableString *newString = [textField.text mutableCopy];
                [newString replaceCharactersInRange:range withString:limitedString];
                textField.text = newString;
            }
            return NO;
        } else {
            return YES;
        }
    }
    

提交回复
热议问题