iOS UiTextField限制输入导致键盘问题

时间:2012-05-15 10:15:05

标签: ios uitextfield

我正在尝试限制用户可以输入的字符数量。我有这个工作,唯一的问题是它现在停止了键盘关闭。例如,我想将输入限制为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);
}

1 个答案:

答案 0 :(得分: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;
}