iOS里 UITextField以特定字符串组成

来源:互联网 发布:公司申请淘宝企业店铺 编辑:程序博客网 时间:2024/04/29 00:44
限制 UITextField的字符串,需要先遵守

UITextFieldDelegate;


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
这个方法来控制的话,比如控制输入10个字符,当输入10个字符的时候,是无法用delete键进行修改的,这种情况下的用户体验很不好;

UIControlEvents有这样一种事件UIControlEventEditingChanged;

因此可以给UITextField添加这样一种方法

[self.wifi_nameaddTarget:selfaction:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];

实现以下方法:

- (void)textFieldDidChange:(UITextField *)textField

{

    //只取特定字符

     NSCharacterSet *cs = [[NSCharacterSetcharacterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-"]invertedSet];

    textField.text = [[textField.textcomponentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    if (textField == self.wifi_name) {

        if (textField.text.length >10) {

            textField.text = [textField.textsubstringToIndex:10];

        }

    }    

}



1 0
原创粉丝点击