Search code examples
iosswiftuikit

What's the best way to dynamically change screen content based on condition in Swift?


I have content stored in a database in certain patterns:

  • [Image, title, body]

  • [body, title]

  • [Image, body]

  • etc.

I need to display this information on the screen in that specific order. The user taps on the right or left side of the screen to navigate to the next content page. This is similar to an Instagram story but text can come in different orders.

Storyboards don't seem super flexible to varying content orders/type. What's the best way to identify the pattern as a certain template form then switch to that? Should the new template be a .xib, storyboard, or coded in?

I've noticed that apps like Medium or blogging sites can place an image or text in any order based on what's written. How is this possible?


Solution

  • I use the UIPageViewController in these cases.
    UIPageViewController is a container view controller that manages navigation between pages of content, where a child view controller manages each page.

    You can create multiple views that you want to construct and show them in child views.

    I'll show you the example code.

    pageController = UIPageViewController.init(transitionStyle: UIPageViewController.TransitionStyle.scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
            
            pageController.view.backgroundColor = UIColor.clear
            pageController.delegate = self
            pageController.dataSource = self
            
            for svScroll in pageController.view.subviews as! [UIScrollView] {
                svScroll.delegate = self
            }
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                
                self.pageController.view.frame = CGRect(x: 0, y: self.viewLine.frame.maxY + self.view.safeAreaInsets.top, width: self.view.frame.size.width, height: self.view.frame.size.height-(self.viewLine.frame.maxY + self.view.safeAreaInsets.top))
            }
            
            tab1VC = self.storyboard?.instantiateViewController(withIdentifier: "MySaveListVC") as? MySaveListVC
            tab2VC = self.storyboard?.instantiateViewController(withIdentifier: "MyReviewListVC") as? MyReviewListVC
            
            
            arrVC = [tab1VC, tab2VC]
            
            pageController.setViewControllers([tab1VC], direction: UIPageViewController.NavigationDirection.forward, animated: false, completion: nil)
            
            self.addChild(pageController)
            self.view.addSubview(pageController.view)
            pageController.didMove(toParent: self)
    

    where tab1 and tab2 are child views.

    You can move the view using buttons or swipe gestures.