Hide UITableView on touches outside the tableview

前端 未结 3 1362
心在旅途
心在旅途 2021-01-25 00:13

I have a small UITableView that is hidden when the view is loaded. When i click on \"SHOW\" UIButton, the UITableView<

相关标签:
3条回答
  • 2021-01-25 00:37

    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

    0 讨论(0)
  • 2021-01-25 00:43

    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.

    0 讨论(0)
  • 2021-01-25 00:44

    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. :)

    0 讨论(0)
提交回复
热议问题