UITextField 限制长度

static int MaxLength = 16;

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.myTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

- (void)textFieldDidChange:(UITextField *)textField{
    //输入中文,即textField.textInputMode.primaryLanguage为:zh-Hans(简体)、zh-Hant(繁体)的时候,如果有占位拼音就退出,不做计算
    if (textField.markedTextRange != nil) {
        return;
    }
NSString
*tempString = textField.text;
//  去掉首尾的空格和回车 //  tempString = [tempString stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
if (tempString.length > MaxLength) { tempString = [tempString substringToIndex:MaxLength]; } textField.text = tempString; } - (void)dealloc { [NSNotificationCenter.defaultCenter removeObserver:self]; }

猜你喜欢

转载自www.cnblogs.com/liuyongfa/p/10031292.html