AaoIi
AaoIi

Reputation: 8396

Reload UITableView inside UIScrollView in Swift

I've a main class called ViewController which is holding the UIScrollView and inside this ViewController I'm defining the three other controllers that is holding UITableViews as following :

let viewController1 = storyboard?.instantiateViewControllerWithIdentifier("ViewController1") as! ViewController1
let viewController2 = storyboard?.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2
let viewController3 = storyboard?.instantiateViewControllerWithIdentifier("ViewController3") as! ViewController3

And then adding them to the scrollview.

I've implemented UIScrollViewDelegate so after finishing from scrolling it refresh my UITableView in that ViewController.

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

    let page = scrollView.contentOffset.x / self.view.frame.width

}

I got the page number, but how do i reload for example if i am in ViewController2 which has UITableView?

Upvotes: 0

Views: 1369

Answers (1)

Steve Wilford
Steve Wilford

Reputation: 9012

Keep an array of view controllers in your ViewController:

var viewControllers = [UIViewController]()

Then set them up and add them to this array:

viewControllers.append(storyboard?.instantiateViewControllerWithIdentifier("ViewController1") as! ViewController1)
viewControllers.append(storyboard?.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2)
viewControllers.append(storyboard?.instantiateViewControllerWithIdentifier("ViewController3") as! ViewController3)

Then you can reference them in your scroll view delegate method:

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
    let page = Int(floor(scrollView.contentOffset.x / self.view.frame.width))
    if page < viewControllers.count {
        let viewController = viewControllers[page]
        // do whatever with viewController
    }
}

Upvotes: 1

Related Questions