0

我试图限制用户可以输入的字符数量。我有这个工作,唯一的问题是它现在停止关闭键盘。例如,我想将输入限制为 3 个字符,我输入两个字符并在键盘上按完成,键盘关闭,但如果我输入 3 个字符并按完成,键盘不会关闭任何关于为什么的想法?

这是我的代码

 (void)viewDidLoad
{
    NSLog(@"%@", self.chosenTime);
    [self startGame];
    [super viewDidLoad];

    self.nameTextField.delegate = self;
      NSLog(@"%@", self.playerName);
    NSString *timeString =  self.chosenTime;
    self.timer = [timeString intValue];
    self.timeSelected = [timeString intValue];
    self.scoreTimer = 1000;
    self.countdown.text = timeString;

    // Do any additional setup after loading the view.
}


- (IBAction)hideKeyboard:(id)sender {
    NSLog(@"Hello");
    [self.nameTextField resignFirstResponder];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    self.playerName = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return !([self.playerName length] >= 4);
}
4

1 回答 1

2

试试这个,把最后两种方法改成这三种:

- (void)hideKeyboardAction {
    [self.nameTextField resignFirstResponder];
}

- (IBAction)hideKeyboard:(id)sender {
    NSLog(@"Hello");
    [self hideKeyboardAction];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    self.playerName = [textField.text stringByReplacingCharactersInRange:range withString:string];

    BOOL shouldStayOpen = !([self.playerName length] >= 4); 

    if (!shouldStayOpen)
    {
        [self hideKeyboardAction];
    }

    return shouldStayOpen;
}
于 2012-05-15T10:25:43.707 回答