简体   繁体   English

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

[英]iOS UiTextField Limit input causing keybard issue

I'm trying to limit the amount of characters that a user can input. 我试图限制用户可以输入的字符数量。 I have that working, the only problem is it's now stopped the keyboard from closing. 我有这个工作,唯一的问题是它现在停止了键盘关闭。 For example I want to restrict input to 3 characters, I type two characters and press done on the keyboard the keyboard closes but if I type 3 characters and press done the keyboard doesn't close any ideas as to why? 例如,我想将输入限制为3个字符,我键入两个字符,然后在键盘上按键完成键盘关闭,但如果我输入3个字符并按完了键盘,键盘不会关闭为什么会有任何想法?

heres my code 继承我的代码

 (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);
}

Try this, change the last two methods to these three: 试试这个,将最后两个方法改为这三个:

- (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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM