Mahdi Aleali
Mahdi Aleali

Reputation: 57

Setup delegates for 2 different UIScrollViews in the same class

I have a UIScrollView and a UITableView(technically also a UIScrollView) in my class. I made the class a UIScrollViewDelegate so it would run some code when the scrollViewDidScroll method is activated. The problem is this code is ran for when both the scroll view and tableView are scrolled but I do not want that to be the case.

Is there any way I could separate those? I looked online and tried to find a way to set the scroll view delegate to anything but self but had no success. Could anyone show me how to do that or any other possible solution to this issue?

Upvotes: 1

Views: 60

Answers (2)

Reinier Melian
Reinier Melian

Reputation: 20804

You can check which object is calling the delegate method, all methods on UIScrollViewDelegate pass the object as parameter ej:

func scrollViewDidScroll(_ scrollView: UIScrollView)
func scrollViewDidZoom(_ scrollView: UIScrollView)
func scrollViewWillBeginDragging(_ scrollView: UIScrollView)
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)

and so on, you need to make a simple check by example

func scrollViewDidScroll(_ scrollView: UIScrollView)
{ 
   if(scrollView == self.yourTableView)
   {
     debugPrint("is tableView")
   }

   if(scrollView == self.yourScrollView)
   {
     debugPrint("is scrollView")
   }
}

Hope this helps

Upvotes: 1

Sam B
Sam B

Reputation: 27598

I am kinda surprised that your scrollViewDidScroll is being called when tableview is scrolled.

Anyways, you can restrict your check using this

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (scrollView == myScrollView) {
    //this is my scrollview do something cool here
   }
}

Upvotes: 1

Related Questions