Limiting NSString to numbers as well as # if chars entered. (code included)

走远了吗. 提交于 2019-12-04 15:22:09

There are many ways to do this, but I think this might be the most understandable:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    // Check for non-numeric characters
    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
    }
    // Check for total length
    NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
    if (proposedNewLength > 10) return NO;
    return YES;
}

The first section essentially check a non-empty string for characters that are not between '0' and '9' if it finds one anywhere in the new string it rejects the edit. The second determines what the length of the text will be if the editing is completed and compares to 10 if it's to high it rejects the edit. If the function passes all those tests then the edit is allowed.

There are no problems with my build until I click my textfield... but I get a green arrow warning stating " thread stopped at breakpoint 1 "

You have apparently set a breakpoint in your textField:shouldChangeCharactersInRange:replacementString: method. If your not familiar with breakpoints they look like this: (The blue arrow on the row numbers column) And you can toggle whether or not they are enabled with the button pictured on the right:

Breakpoints are very handy, and I suggest you learn to use them. But for now simply click on the breakpoint and drag it from the column, like an icon from the dock, or toggle that option off.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!