限制UITextfield的輸入字符爲50個字符

1.實現UITextfieldDelegatespa

2.在UITextfield的代理方法中判斷添加字符仍是刪除字符,從而作不一樣的操做代理

#pragma mark-UITextfield的代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger index = range.location + range.length;
    if (index < 50) {
        return YES;
    } else {
        //判斷臨界值的時候是添加文字仍是刪除文字
        if (string.length==0) {
            //刪除文字
            return YES;
        }
        
        //當location==50 string.length>0時須要提示
        
        [MBProgressHUD showError:@"輸入的字符長度不能超過50"];
        return NO;
    }
}
相關文章
相關標籤/搜索