PREFIX文本字段,其值为无法删除

时间:2014-04-11 12:21:25

标签: ios objective-c uitextfield nsnotificationcenter uitextfielddelegate

我有以下代码似乎无法正常工作

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
        if ((textField.text.length == defaultPrefix.length) && [string isEqualToString:@""]) {//When detect backspace when have one character.
            textField.text=defaultPrefix;
        }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

        if (textField.text.length == 0) {
            textField.text = defaultPrefix;
        }
    return YES;
}

defaultPrefix是一个NSString *值,取自UIPickerView。当我尝试删除defaultPrefix值时,textField未填充prefixValue。我做错了什么?

1 个答案:

答案 0 :(得分:0)

在我看来,更好的解决方法是将NSNotificationCenterUITextFieldTextDidChangeNotification一起使用

然后,您可以将此代码添加到viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultPrefix:) name:UITextFieldTextDidChangeNotification object:self.textField];
self.textField.text = self.defaultPrefix;

然后,您只需要添加选择器方法,例如:

- (void) defaultPrefix: (NSNotification*) notification
{
    UITextField *notificationTextField = [notification object];    
    if (notificationTextField == self.textField)
    {
        if ([self.textField.text length] <= [self.defaultPrefix length])
        {
            self.textField.text = self.defaultPrefix;
        }
    }
}

您可以查看示例here