0

我有UITabBarController四个相关的观点。在其中一个视图中,有一个文本视图,它只为navigationbar: 我想做的是在navigationbar触摸时隐藏键盘。我怎样才能做到这一点?我应该重写的touchesBegan:方法UINavigationBar吗?

编辑


我发现这样做的最好方法是添加一个UITapGestureRecognizer

UITapGestureRecognizer* tapRecon = [[UITapGestureRecognizer alloc]
                                    initWithTarget:self action:@selector(navigationBarTap:)];
tapRecon.numberOfTapsRequired = 1;
[self.navigationController.navigationBar addGestureRecognizer:tapRecon];

调用方法

- (void)navigationBarTap:(UIGestureRecognizer*)recognizer { 
     [self.view endEditing:YES]; 
}
4

5 回答 5

2
UITapGestureRecognizer* tapRecon = [[UITapGestureRecognizer alloc]
                                    initWithTarget:self action:@selector(navigationBarTap:)];
tapRecon.numberOfTapsRequired = 1;
[self.navigationController.navigationBar addGestureRecognizer:tapRecon];


- (void)navigationBarTap:(UIGestureRecognizer*)recognizer {
     [self.view endEditing:YES];

    // OR

    for (id view in self.view.subviews) {
        if ([view isKindOfClass:[UITextView class]] || [view isKindOfClass:[UITextField class]]) {
            [view resignFirstResponder];
        }
    }
}

愿这对你有帮助

于 2013-08-02T12:58:58.577 回答
1

在外部单击时,您可以使用此快速扩展来关闭键盘。用户可以点击导航栏或 viewcontroller 视图。

只需在 UIViewController 中调用一次hideKeyboardWhenTappedAround()

extension UIViewController {
    func hideKeyboardWhenTappedOutsides() {
       let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard(_:)))
       tap.cancelsTouchesInView = false
       // On viewcontroller view
       view.addGestureRecognizer(tap)
       // On navigationcontroller view
       self.navigationController?.view.addGestureRecognizer(tap)
}

@objc func dismissKeyboard(_ sender: UITapGestureRecognizer) {
    view.endEditing(true)
    if let navController = self.navigationController {
        navController.view.endEditing(true)
    }
}

}

于 2019-04-16T06:58:50.040 回答
0

未测试。将点击手势添加到 UINavigationbar 和手势动作以辞职响应者。

 UITapGestureRecognizer *gestureRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyboard)];
    gestureRecognizer.numberOfTapsRequired=1;
    gestureRecognizer.cancelsTouchesInView = NO;
    [UInavigationbar addGestureRecognizer:gestureRecognizer];
    [gestureRecognizer release];

行动:

[Textfield resignfirstresponder]
于 2013-08-02T13:02:13.623 回答
0

在您的 touchesBegan 方法中,您可以 resignFirstResponder 使键盘消失。希望这会有所帮助,吉姆欢呼。

于 2013-08-02T12:57:09.987 回答
0

// 此方法将在导航到其他视图之前调用...

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [yourTextField resignFirstResponder];
}

// 这将在导航到其他屏幕之前退出键盘..

我希望这能帮到您。

于 2013-08-02T13:03:20.840 回答