1

I currently have a UITableView whose HeaderView is a UIScrollView. I am using this as a sort of carousel that displays constantly rotating information triggered to move on a timer every two seconds. What I am trying to do is detect when the user has moved the scroll view on their own. Here is the code I have to handle the ScrollView movement right now.

override func viewDidLoad() {
    var myTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)
}
func runTimedCode() {
    var itemCount = newsArray.count // how many items are in the news reel
    if currentPage < itemCount {
        let newX = CGFloat(currentPage) * self.view.frame.width // calculate next page position
        featuredScrollView.setContentOffset(CGPoint(x: newX, y: 0), animated: true)
        currentPage += 1
    } else {
        // end of items
        currentPage = 0
        let newX = CGFloat(currentPage) * self.view.frame.width // calculate next page position
        print("new x = \(newX)")
        featuredScrollView.setContentOffset(CGPoint(x: newX, y: 0), animated: true)
    }
}

However the scrollViewDidScroll function is only called when the tableview is moved. Is there any way to detect when the ScrollView above the tableView is scrolled? I'm completely stuck on this any help is appreciated. Thanks!

Interface Builder view

Mbusi Hlatshwayo
  • 554
  • 1
  • 10
  • 23
  • 1
    have you set the delegate of the scroll view? – koropok May 16 '17 at 01:15
  • @koropok facepalm... I completely forgot. That fixed the issue. I guess the next question I have is how to differentiate between when the tableView is scrolled and when the ScrollView about is scrolled? – Mbusi Hlatshwayo May 16 '17 at 01:21
  • 1
    Have you looked at this? Not sure if it's a solution, but I think the answer is probably a derivative of this. http://stackoverflow.com/a/7706175/4475605 – Adrian May 16 '17 at 01:27
  • 1
    Here's another interesting one. http://stackoverflow.com/a/41124033/4475605 – Adrian May 16 '17 at 01:33

1 Answers1

1

First, make sure that you have the delegate set up so that your view controller gets events from both the scroll view and the table view.

Next, keep references to make sure that you can distinguish the two views.

Finally, check which reference is triggering the viewdidscroll function and do your code there.

let view1:UIScrollView!
let view2:UITableView!

view1.delegate = self
view2.delegate = self

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == view1 {
        // Do something
    }
    if scrollView == view2 {
        // Do something
    }
}
Leo
  • 336
  • 3
  • 6