方法一:TextField的代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *tempStr = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
if (![string isEqualToString:tempStr]) {
return NO;
}
return YES;
}
方法二:TextField添加点击方法,类似于Button的addTarget方法。
[self.textField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
// 自定义的方法,替换空的字符串
- (void)textFieldChange:(UITextField *)textField {
textField.text =[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
}