-1

I'm working on a quote app, I want the pages, except the first one, to be randomized. I don't want people opening the app to see the same initial quotes over and over again. If you could respond with edit to the code I would really appreciate it. Thank you in advance!

import UIKit

class ModelController: NSObject, UIPageViewControllerDataSource {

    let pageData:NSArray = ["All quotes are from Kanye West, Enjoy!", "I refuse to accept other people's ideas of happiness for me. As if there's a 'one size fits all' standard for happiness","I am the greatest","I still think I'm the greatest.","They say you can rap about anything except for Jesus, that means guns, sex, lies, video tapes, but if I talk about God my record won't get played Huh?"]



override init() {
    super.init()

}

func viewControllerAtIndex(_ index: Int, storyboard: UIStoryboard) -> DataViewController? {
    // Return the data view controller for the given index.
    if (self.pageData.count == 0) || (index >= self.pageData.count) {
        return nil
    }

    // Create a new view controller and pass suitable data.
    let dataViewController = storyboard.instantiateViewController(withIdentifier: "DataViewController") as! DataViewController
    dataViewController.dataObject = self.pageData[index] as! String
    return dataViewController
}

func indexOfViewController(_ viewController: DataViewController) -> Int {
    // Return the index of the given data view controller.
    // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index.
    return pageData.index(of: viewController.dataObject) 
}

// MARK: - Page View Controller Data Source

func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
    var index = self.indexOfViewController(viewController as! DataViewController)
    if (index == 0) || (index == NSNotFound) {
        return nil
    }

    index -= 1
    return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    var index = self.indexOfViewController(viewController as! DataViewController)
    if index == NSNotFound {
        return nil
    }

    index += 1
    if index == self.pageData.count {
        return nil
    }
    return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)

1 Answers1

1

You can randomise your quote array and pass on the randomised array. Checkout these link: How do I shuffle an array in Swift? and Shuffle array swift 3

Community
  • 1
  • 1
Navneet Gill
  • 393
  • 1
  • 13