52

I want to detect if mytable view has been scrolled, I tried all touch events like this one:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  {
    [super touchesBegan:touches withEvent:event];
    //my code
  }

but it seems that all touch events don't response to scroll but they response only when cells are touched, moved,...etc

Is there a way to detect scroll event of UITableView ?

1

3 Answers 3

135

If you implement the UITableViewDelegate protocol, you can also implement one of the UIScrollViewDelegate methods:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

or

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

For example, if you have a property called tableView:

// ... setting up the table view here ...
self.tableView.delegate = self;
// ...

// Somewhere in your implementation file:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    NSLog(@"Will begin dragging");
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"Did Scroll");
}

This is because UITableViewDelegate conforms to UIScrollViewDelegate, as can be seen in the documentation or in the header file.

2
  • 1
    What about when we have more than one UITableView?
    – Solidus
    Commented Dec 6, 2012 at 20:02
  • 1
    You should be able to set the delegate of both table views to self and then check which one was scrolled using the scrollView that is passed. See here.
    – fabian789
    Commented Dec 7, 2012 at 6:45
9

These are the methods from UITableViewDelegate using Swift to detect when an UITableView will scroll or did scroll:

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

}

func scrollViewDidScroll(_ scrollView: UIScrollView) {

}
8

If you have more than one table views as asked by Solidus, you can cast the scrollview from the callback to tableview as UITableView is derived from UIScrollView and then compare with the tableviews to find the source tableview.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {    
        UITableView* fromTableView = (UITableView*) scrollView;
        UITableView* targetTableView = nil;
        if (fromTableView == self.leftTable) {
            targetTableView = self.leftTable;
        } else {
            targetTableView = self.rightTable;
        }
...
}
1
  • 1
    A small note: in order for the == comparison to work you don't have to cast.
    – Arik Segal
    Commented Oct 15, 2019 at 12:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.