How to remove UITableViewCell swipe to delete bounce

前端 未结 3 1287
孤城傲影
孤城傲影 2021-02-10 10:29

The new \'swipe to delete\' look and feel in iOS 7 added a \'bounce\' effect where the UITableViewCell continues to offset after a swipe. Is there any way to disable this bounce

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-10 10:40

    I think I finally found a solution! Using a custom cell, you can set that cell as a UIScrollViewDelegate and implement the scrollViewDidScroll: method. In that method, you can force the UIScrollView's contentOffset to stay under a particular value (I'm using 82.0f because that seems to be the contentOffset when the 'Delete' button is fully visible). Like this:

    .h

    @interface MyCustomCell : UITableViewCell 
    

    .m

    -(void)awakeFromNib{
        [super awakeFromNib];
    
        for(UIView *subview in self.subviews){
            if([subview isKindOfClass:[UIScrollView class]]){
                UIScrollView *theScrollView = (UIScrollView *)subview;
                theScrollView.delegate = self;
            }
        }
    }
    
    #pragma mark - UIScrollViewDelegate
    
    -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
        static CGFloat kTargetOffset = 82.0f; 
    
        if(scrollView.contentOffset.x >= kTargetOffset){
            scrollView.contentOffset = CGPointMake(kTargetOffset, 0.0f);
        }
    }
    

    This can also be done without using a custom cell by simply setting a ViewController as a UIScrollViewDelegate and setting the UIScrollView's delegate in tableView:cellForRowAtIndexPath like so:

    .h

    MyViewController : UIViewController 
    

    .m

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *cellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
        if(cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        }
    
        for(UIView *subview in cell.subviews){
            if([subview isKindOfClass:[UIScrollView class]]){
                UIScrollView *theScrollView = (UIScrollView *)subview;
                theScrollView.delegate = self;
            }
        }
    
        return cell;
    }
    
    #pragma mark - UIScrollViewDelegate
    
    -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
        static CGFloat kTargetOffset = 82.0f;
    
        if(scrollView.contentOffset.x >= kTargetOffset){
            scrollView.contentOffset = CGPointMake(kTargetOffset, 0.0f);
        }
    }
    

提交回复
热议问题