无法用shouldChangeCharactersInRange隐藏键盘

时间:2012-05-24 05:40:51

标签: iphone objective-c ios xcode uitextfield

这是我的代码:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"אבגדהוזחטיכלמנסעפצקרשתףץםן"] invertedSet];

    // max charcters
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    if (newLength > 14)
        return NO;

    // allow backspace
    if (range.length > 0 && [string length] == 0) {
        return YES;
    }
    // do not allow . at the beggining
    if (range.location == 0 && [string isEqualToString:@"."]) {
        return NO;
    }
    if ((range.location > 0) && (([[textField.text substringWithRange:NSMakeRange((range.location -1), 1)] isEqualToString:@"ף"]) || ([[textField.text substringWithRange:NSMakeRange((range.location -1), 1)] isEqualToString:@"ץ"]) || ([[textField.text substringWithRange:NSMakeRange((range.location -1), 1)] isEqualToString:@"ם"]) || ([[textField.text substringWithRange:NSMakeRange((range.location -1), 1)] isEqualToString:@"ן"])))   
    {
        return NO;
    }

    // set the text field value manually
    NSString *newValue = [[textField text] stringByReplacingCharactersInRange:range withString:string];
    newValue = [[newValue componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:@""];
    textField.text = newValue;
    // return NO because we're manually setting the value
    return NO;
}

我只想点击返回键盘就会消失。我做不到。在哪里添加它以及如何添加?

3 个答案:

答案 0 :(得分:7)

如果要在点按return键后隐藏键盘,请在代码中添加以下内容:

if ([string isEqualToString:@"\n"]) {
    [theTextField resignFirstResponder];
    return NO;
}

希望有所帮助

答案 1 :(得分:3)

在UITextField的委托方法中使用textFieldShouldReturn: -

[yourTextField resignFirestResponder];

还要在您的类中实现UITextFieldDelegate,并将viewDidLoad中的委托设置为: -

yourTextField.delegate=self;

答案 2 :(得分:1)

创建IBAction并将其与TextField视图连接。

-(IBAction)doneEditing:(id)sender
{
     [sender resignFirstResponder];
}

连接到文件所有者时,选择事件在退出上结束。