Можно ли иметь бесконечный горизонтальный просмотр страниц для управления страницами в swift 4? - PullRequest
0 голосов
/ 29 октября 2018

Скажем, у меня есть массив строк, и каждый раз, когда я пролистываю, я хочу, чтобы текст на экране был случайной строкой из массива, не доходя до конца. Как бы я это сделал?

Ответы [ 2 ]

0 голосов
/ 30 октября 2018

Вы можете сделать это с помощью UIPageViewController.

Вот простой пример (добавьте UIPageViewController к вашей раскадровке и установите для него Class InfinitePageViewController):

//
//  InfinitePageViewController.swift
//  InfinitePages
//
//  Created by Don Mag on 10/30/18.
//

import UIKit

// simple random color extension
extension UIColor {
    static func randomColor(saturation: CGFloat = 1, brightness: CGFloat = 1, alpha: CGFloat = 1) -> UIColor {
        let hue = CGFloat(arc4random_uniform(361)) / 360.0
        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
    }
}

class SinglePageViewController: UIViewController {

    var theLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .white
        v.textAlignment = .center
        v.numberOfLines = 0
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.randomColor()

        view.addSubview(theLabel)
        NSLayoutConstraint.activate([
            theLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 40.0),
            theLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -40.0),
            theLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0),
            theLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40.0),
            ])

    }

}

class InfinitePageViewController: UIPageViewController, UIPageViewControllerDataSource {

    var stringArray = [
        "1 - Do not consider painful what is good for you.",
        "2 - It is better to look ahead and prepare than to look back and regret.",
        "3 - The easiest thing in the world to be is you. The most difficult thing to be is what other people want you to be. Don't let them put you in that position.",
        "4 - A book is a version of the world. If you do not like it, ignore it; or offer your own version in return.",
        "5 - The scientific name for an animal that doesn't either run from or fight its enemies is lunch.",
        "6 - To love is to receive a glimpse of heaven.",
        "7 - Patriotism is your conviction that this country is superior to all other countries because you were born in it.",
        "8 - There is but one temple in the universe and that is the body of man.",
        "9 - It is easier to get forgiveness than permission.",
        "10 - There is always more misery among the lower classes than there is humanity in the higher.",
        "11 - Success is counted sweetest by those who ne'er succeed.",
        "12 - Indifference and neglect often do much more damage than outright dislike.",
        "13 - For what do we live, but to make sport for our neighbours, and laugh at them in our turn?",
        "14 - Last night somebody broke into my apartment and replaced everything with exact duplicates... When I pointed it out to my roommate, he said, 'Do I know you?'",
        "15 - Do not weep; do not wax indignant. Understand.",
        "16 - Work saves us from three great evils: boredom, vice and need.",
        "17 - You can discover what your enemy fears most by observing the means he uses to frighten you.",
        "18 - Rest satisfied with doing well, and leave others to talk of you as they please.",
        "19 - People want economy and they will pay any price to get it.",
        "20 - On the whole human beings want to be good, but not too good, and not quite all the time.",
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.dataSource = self

        // create the first "page"
        let vc = SinglePageViewController()
        vc.theLabel.text = stringArray[0]

        // set it as the initial page VC
        self.setViewControllers([vc], direction: .forward, animated: false, completion: nil)

    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        // don't allow scrolling backward
        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        let vc = SinglePageViewController()
        let randomIndex = Int(arc4random_uniform(UInt32(stringArray.count)))
        vc.theLabel.text = stringArray[randomIndex]
        return vc
    }

}

Это будет прокручиваться бесконечно, выбирая случайную строку из stringArray для каждой новой страницы.

Поскольку это просто получение случайной строки из массива, вполне возможно, что вы получите одну и ту же строку несколько раз - даже последовательно. Если вы не хотите этого, один из подходов состоит в том, чтобы перетасовать массив индексных чисел, а затем пройти через этот массив. Когда вы дойдете до конца, снова перемешайте номера и продолжайте.

0 голосов
/ 29 октября 2018

Нет, вы не можете иметь бесконечное представление прокрутки. UIScrollView - это вид на прямоугольную область. Эта прямоугольная область может быть большой, но у нее есть пределы.

A UIPageViewController может делать то, что вы хотите. Прошло много времени с тех пор, как я его использовал, но, глядя на документы, похоже, что вы можете либо предоставить массив контроллеров представления, либо предоставить dataSource, который соответствует протоколу UIPageViewControllerDataSource. Похоже, вы могли бы использовать dataSource для обслуживания бесконечного набора контроллеров представления, содержащих ваши строки.

...