0

当用户按下“取消”UIBarButtonItem 时,我试图关闭键盘。但是,当我单击取消按钮时,我收到一个带有“无法识别的选择器发送到实例”错误的 SIGABRT。

我创建取消按钮的代码是:

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    //Add cancel button to navigation bar
    UIBarButtonItem *dismissKeyboardBttn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(dismissKeyboard:)];
    self.navigationItem.rightBarButtonItem = dismissKeyboardBttn;
}

要关闭键盘,我有这种方法:

- (void)dismissKeyboard:(id)sender
{
    [activeField resignFirstResponder];
    //^^This line causes the SIGABRT^^
}

这似乎很简单。有任何想法吗?

更新:activeField 只是我用来将我的滚动视图移动到用户当前正在编辑的 UITextField 的 UITextField。在这两种方法中设置:

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    activeField = textField; 
}
- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    activeField = nil; 
}

更新 2:有趣的是,我已经注册了 ViewController 以接收键盘通知,当我尝试使用“textFieldShouldReturn”方法关闭键盘时,我得到了同样的错误。这是我的 textFieldShouldReturn 代码:

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

    if ([textField canResignFirstResponder])
    {
        [textField resignFirstResponder];
    }

    return YES;
}
4

3 回答 3

1

什么是活动场?如果是 UIResponder,它应该响应 resignFirstResponder。所以也许不是。UIViews 和 UIViewControllers 是 UIResponders。

于 2011-10-06T15:50:03.060 回答
1

我处于一种情况,并在当前视图控制器中执行以下操作:

在头文件中,为成为第一响应者的文本字段创建一个 IBAction 并调出键盘:

- (IBAction)textFieldDidBeginEditing:(UITextField *)textField;

在实现文件中,创建一个创建栏按钮(在我的例子中是“完成”按钮)并将其添加到导航栏右侧的方法。同时,我在TextField(已成为第一响应者)之间创建了一个目标动作配对

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    // create new bar button with "Done" as text
    // set the target of the action as the text field (since we want the text field to resign first responder status and dismiss the keyboard)
    // tell the text field to resign with the stock 'resignFirstResponder' selector
    UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                         target:textField
                                                                         action:@selector(resignFirstResponder)];

    // add the button with target/action pairing to the navigation bar
    [[self navigationItem] setRightBarButtonItem:bbi];
}

此外,如果您希望按钮在我单击它后消失(并且键盘消失),我使用textFieldDidEndEditing ,因为编辑现在已通过第一响应者识别完成:

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [[self navigationItem] setRightBarButtonItem:nil];
}
于 2012-12-19T03:25:50.007 回答
0

晨星是对的,什么是activeField,它是一个id,你可能需要添加一个演员:(UIButton*)?另外,我总是在以下时候添加这个resignFirstResponder

if(myObject canResignFirstResponder){

}
于 2011-10-06T16:14:05.733 回答