theflarenet theflarenet - 7 months ago 21
Swift Question

Live Detection of scrollView position in panned view

I have a panned UIViewController at the initial launch that loads up two individual XIB views which the user can swipe to traverse through. I'd like to trigger code once the user swipes 2/3 across the total width (panned width of both views) but my detection isn't live.

Here's my code so far...

let vc0 = ViewController0(nibName: "ViewController0", bundle: nil)
let vc1 = ViewController1(nibName: "ViewController1", bundle: nil)

class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
super.viewDidLoad()

self.addChildViewController(vc0)
self.scrollView.addSubview(vc0.view)
vc0.didMoveToParentViewController(self)

var frame1 = vc1.view.frame
frame1.origin.x = self.view.frame.size.width
vc1.view.frame = frame1


self.addChildViewController(vc1)
self.scrollView.addSubview(vc1.view)
vc1.didMoveToParentViewController(self)

self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 2, self.view.frame.size.height - 66)

// This doesn't work
scrollView.delegate = self


// If the user user swipes 2/3 in (or it can be any other offset that's practical)
if (scrollView.contentOffset.x > (self.view.frame.size.width*2)*(2/3)) {
// Code I'd like to execute
// ...
}
}


How is this possible with Swift?

Answer

You should set the delegate of the scroll view using

scrollView.delegate = self

and declare that your class implements UIScrollViewDelegate:

class ViewController: UIViewController, UIScrollViewDelegate

Then implement scrollViewDidScroll which is called every time your scrollview's scrolling is changed.

func scrollViewDidScroll(scrollView: UIScrollView) {
   // If the user user swipes 2/3 in (or it can be any other offset that's practical)
   if (scrollView.contentOffset.x > (self.view.frame.size.width*2)/(2/3)) {
     // Code I'd like to execute
     // ...
   }
}