iOS

iOS UITextField 常规处理

学习笔记

Posted by Asingers on January 5, 2017
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    if ([textField.text rangeOfString:@"."].location == NSNotFound)
    {
        isHaveDian = NO;
    }
    if ([string length] > 0)
    {
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.')//数据格式正确
        {
            //首字母不能为0和小数点
            if([textField.text length] == 0)
            {

                if(single == '.')
                {

                    [self showMyMessage:@"亲,第一个数字不能为小数点!"];

                    [textField.text stringByReplacingCharactersInRange:range withString:@""];

                    return NO;

                }

                if (single == '0')
                {

                    [self showMyMessage:@"亲,第一个数字不能为0!"];

                    [textField.text stringByReplacingCharactersInRange:range withString:@""];

                    return NO;

                }

            }

            //输入的字符是否是小数点

            if (single == '.')
            {

                if(!isHaveDian)//text中还没有小数点
                {

                    isHaveDian = YES;

                    return YES;

                }else{

                    [self showMyMessage:@"亲,您已经输入过小数点了!"];

                    [textField.text stringByReplacingCharactersInRange:range withString:@""];

                    return NO;

                }

            }else{

                if (isHaveDian) {//存在小数点

                    //判断小数点的位数

                    NSRange ran = [textField.text rangeOfString:@"."];

                    if (range.location - ran.location <= 2) {

                        return YES;

                    }else{

                        [self showMyMessage:@"亲,您最多输入两位小数!"];

                        return NO;

                    }

                }else{

                    return YES;

                }

            }

        }else{//输入的数据格式不正确

            [self showMyMessage:@"亲,您输入的格式不正确!"];

            [textField.text stringByReplacingCharactersInRange:range withString:@""];

            return NO;

        }

    }

    else

    {

        return YES;

    }

}

-(void)showMyMessage:(NSString*)aInfo {

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:aInfo delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

    [alertView show];

}
文章使用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议