Roduck Nickes
Roduck Nickes

Reputation: 1021

Detect when view appear on screen

So I am using this Github package: https://github.com/jakespracher/Snapchat-Swipe-View

And I have a problem. viewDidLoad and viewDidAppear does only run once, when the application has loaded. How can I run a code every time the let left = storyboard.instantiateViewControllerWithIdentifier("left") appears on the screen?

Upvotes: 1

Views: 3300

Answers (3)

Codebear
Codebear

Reputation: 196

Snapchat-Swipe-View loads all of the viewControllers and views into scrollView of SnapContainerViewController at once.

All of the viewControllers are childViewController of SnapContainerViewController.

therefore

  1. all viewControllers will received viewDidLoad and viewDidAppear at once

  2. technically all viewControllers are already at "appear" state, it won't call "viewDidAppear" again before "viewDidDisappear"

  3. paging change(switching view to on-screen) can be identified from scrolling event.

Example to identify which viewController is on-screen (for horizontal scrollview with index 0, 1, 2) Similar handling for vertical scrollView.

Simply add the following callback method in SnapContainerViewController.swift

extension SnapContainerViewController: UIScrollViewDelegate {
   func scrollViewDidEndDecelerating(scrollView: UIScrollView){
        let fullWidth = scrollView.frame.size.width
        let pageNo: NSInteger = lround(Double(scrollView.contentOffset.x / fullWidth))

        print("page is shown:", pageNo)
    }

Upvotes: 1

Idan
Idan

Reputation: 5450

Like you say, each ViewController is loaded when the app is loaded, the view is magnified and you only scroll between the View Controllers. Therefore, you are missing the benefits of UIViewController class. Your best bet is:

  1. To get the screen location by setting property listeners to the center of the UIScrollView, see Understanding UIScrollView.
  2. Set timer for the change or recognize touch.
  3. Use a better project, and modify it to your needs

Upvotes: 0

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7746

I believe the viewWillAppear method will still run every time. Otherwise you could use viewDidLayoutSubviews.

Upvotes: 1

Related Questions