输入框UITextField禁止输入空格方法

时间:2022-06-17 19:28:57

方法一:添加代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];

if (![string isEqualToString:tem]) {

return NO;

}

return YES;

}

方法二:

[self.searchTextField addTarget:self action:@selector(searchTextFieldChange:) forControlEvents:UIControlEventEditingChanged];

在searchTextFieldChange方法中   直接替换空的字符串

- (void)searchTextFieldChange:(UITextField *)textField{

textField.text =[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];

}