UITextField设置无法输入空格

1.在UITextFieldDelegate的代理方法中设置过滤空格

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *textPsw = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([textPsw length] == 0) {
        return NO;
    }
    return YES;
}

此时虽然不能输入空格,但是出现点击删除键却无法删除的问题,解决如下:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *textPsw = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (range.length == 1 && textPsw.length == 0) {
        return YES;
    }
    if ([textPsw length] == 0) {
        return NO;
    }
    return YES;
}



你可能感兴趣的:(#,iOS开发小结,uitextfield,iOS,不输入空格,无法删除)