简体   繁体   中英

Hide UITableView on touches outside the tableview

I have a small UITableView that is hidden when the view is loaded. When i click on " SHOW " UIButton , the UITableView is made visible by myTableView.hidden=NO;

I want to hide UITableView when a user touches outside its frame. Thanks for any help!

You can get touch position by this:

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

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
 { 
   CGPoint touchPoint=[gesture locationInView:self.View];
 }

Then just check if the point is in tableview frame. If not then hide the tableview . Hope this help. :)

Best Approach

Simple.Before show up the UITable View add one more grayed out/Transparent view then add tap gesture recogniser on it to hide it . That's it.

  1. Show Overlay View first - alpha will be 0.5f and background color should be clear color.

  2. show the table view.

NOTE: over lay view should have tap recogniser which will hide the overlay and table view

in View did load

UITapGestureRecognizer *tapRecog = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(overlayDidTap:)];

[myOverLayView addGestureRecognizer:tapRecog];



- (void)overlayDidTap:(UITapGestureRecognizer *)gesture
{

    //hide both overlay and table view here

}

Bad Approach

We should not add tap recogniser on main view itself. Because it may have lots of controls inside of it. so when user tap on it. it will perform its operation. So to avoid it we can simulate the same behaviour by above approach

Subclass UITableView , override pointInside:withEvent: . It is templated for this reason.

Something like:

-(BOOL)pointInside:(CGPoint) point withEvent:(UIEvent*) event
{
    BOOL pointIsInsideTableView = [super pointInside:point withEvent:event];
    BOOL pointIsOutsideTableView = // Some test
    return pointIsInsideTableView || pointIsOutsideTableView;
}

So you can catch the touch in table view implementation, where it belongs logically in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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