开发者

Make UIView resign first responder when tapped outside of view

开发者 https://www.devze.com 2023-01-10 20:18 出处:网络
Is th开发者_如何学编程ere any way to make a UIView resign its first responder status when the user taps outside of the view bounds?Capture the touch in the other view or views. When handling that touc

Is th开发者_如何学编程ere any way to make a UIView resign its first responder status when the user taps outside of the view bounds?


Capture the touch in the other view or views. When handling that touch, call a selector that has your view resign its responder status.


Found better answer when doing research...

Get the current first responder without using a private API

there is sample code on how to navigate the views to find the first-responder which could be used as the basis of you solution

You could place a transparent view first, then your view as a sub view. Then any touch events in the transparent view could be used to resign first responder.

This might be an approach if there are multiple views, outside the boundary of the primary view to be managed


This is quite straight forward and needs to be covered in two steps:

  1. Add a gesture recogniser to catch the view tap
  2. Resign the first responder

Thanks to @Nathan Eror for the first part. We can add a gesture recogniser to the viewDidLoad method to register when the user taps the screen:

UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];

Next we will add the function to detect this and the code to remove the keyboard:

- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
CGPoint location = [recognizer locationInView:[recognizer.view superview]];

    [textField resignFirstResponder];
}

It is worth noting that if you have multiple textFields in your view you will need to resign them all as there is no way of the touch knowing which is the current first responder.


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [yourtextfield resignFirstResponder];
    //You can have multiple textfields in here
}
0

精彩评论

暂无评论...
验证码 换一张
取 消