发布我的替代解决方案,因为我遇到了 OP 的确切问题,并发现我不必在所选答案中详细说明任何光标位置更改。
下面是 UITextFieldDelegate 方法,我调用了一个自定义委托方法 didChangeValueForTextField,因为我要启用的按钮在此类之外。
实现 UITextFieldDelegate 的类
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newValue = [textField.text stringByReplacingCharactersInRange:range withString:string];
BOOL shouldReturn = YES;
if (range.location > 0 && range.length == 1 && string.length == 0){
[textField deleteBackward];
if ([textField.text isEmptyCheck]) { // Check if textField is empty
newValue = @"";
}
shouldReturn = NO;
}
if(self.delegate && [self.delegate respondsToSelector:@selector(didChangeValueForField:withNewValue:)]) {
[self.delegate didChangeValueForField:textField withNewValue:newValue];
}
return shouldReturn;
}
关键是检测安全字段单字符删除和触发字段清除的安全字段单字符删除之间的区别。在上述委托方法中检测到这一点是必要的。
包含要启用的按钮的类
- (void)didChangeValueForField:(UITextField *)textField withNewValue:(NSString *)value {
// Update values used to validate/invalidate the button.
// I updated a separate model here.
// Enable button based on validity
BOOL isEnabled = [self allFieldsValid]; // Check all field values that contribute to the button being enabled.
self.myButton.enabled = isEnabled;
}