В UIPageViewController анимация start-stop работает неправильно - PullRequest
0 голосов
/ 06 марта 2020

Я создал PageViewController и добавил ViewController1 как страницы, на которые я добавил две кнопки на ViewController1, чтобы запустить и приостановить анимацию, поэтому, если я запустил анимацию и проведу пальцем по паре страниц, затем вернусь и запустите анимацию, которая не работает, я не знаю почему?

введите описание изображения здесь

Итак, в Gif я нажимаю на первой странице, начиная анимацию, затем нажимаю паузу кнопку, а затем я пролистываю страницы и снова возвращаюсь на ту же страницу, и если нажата анимация запуска, ничего не происходит.

Я добавил проект на GitHub https://github.com/patelashish797/UIPageDemo

Спасибо


class PageViewController: UIPageViewController, UIPageViewControllerDataSource,UIPageViewControllerDelegate {

    var pages = [UIViewController]()
    let pageControl = UIPageControl()

         init(transitionStyle style:
            UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [String : Any]? = nil) {
                super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
            }
            required init?(coder: NSCoder) {
                fatalError("init(coder:) has not been implemented")
            }


    override func viewDidLoad() {
       super.viewDidLoad()
            self.dataSource = self
            self.delegate = self
            let initialPage = 0
            let page1 = ViewController1()
            page1.name = "Ashish"
            let page2 = ViewController1()
            page2.name = "Bunty"
            let page3 = ViewController1()
            page3.name = "Patel"

            // add the individual viewControllers to the pageViewController
            self.pages.append(page1)
            self.pages.append(page2)
            self.pages.append(page3)
            setViewControllers([pages[initialPage]], direction: .forward, animated: true, completion: nil)

             // pageControl
             self.pageControl.frame = CGRect()
             self.pageControl.currentPageIndicatorTintColor = UIColor.black
             self.pageControl.pageIndicatorTintColor = UIColor.lightGray
             self.pageControl.numberOfPages = self.pages.count
             self.pageControl.currentPage = initialPage
             self.view.addSubview(self.pageControl)

             self.pageControl.translatesAutoresizingMaskIntoConstraints = false
             self.pageControl.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -5).isActive = true
             self.pageControl.widthAnchor.constraint(equalToConstant: 70).isActive = true
             self.pageControl.heightAnchor.constraint(equalToConstant: 20).isActive = true
             self.pageControl.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

        if let viewControllerIndex = self.pages.firstIndex(of: viewController) {
            if viewControllerIndex == 0 {
                // wrap to last page in array
                return self.pages.last
            } else {
                // go to previous page in array
                return self.pages[viewControllerIndex - 1]
            }
        }
        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {

        if let viewControllerIndex = self.pages.firstIndex(of: viewController) {
            if viewControllerIndex < self.pages.count - 1 {
                // go to next page in array
                return self.pages[viewControllerIndex + 1]
            } else {
                // wrap to first page in array
                return self.pages.first
            }
        }
        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {

    // set the pageControl.currentPage to the index of the current viewController in pages
        if let viewControllers = pageViewController.viewControllers {
            if let viewControllerIndex = self.pages.firstIndex(of: viewControllers[0]) {
                self.pageControl.currentPage = viewControllerIndex
            }
        }
    }


}

class ViewController1: UIViewController {

    var name: String?

    let array = [#colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1),#colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1),#colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1),#colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)]

    lazy var animator: UIViewPropertyAnimator = UIViewPropertyAnimator(duration: 5, curve: .linear) {
        self.labelInst.transform = CGAffineTransform(rotationAngle: -180 * .pi / 180)
    }
    let labelInst = UILabel()

    override func viewWillAppear(_ animated: Bool) {
        print("viewWillAppear page 1")
    }

    let startButton: UIButton = {
        let button = UIButton()
        button.setTitle("start", for: .normal)
        button.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        button.addTarget(self, action: #selector(onTapStart), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    @objc func onTapStart() {
        print("you hit start")
        animator.startAnimation()
    }

    let pauseButton: UIButton = {
        let button = UIButton()
        button.setTitle("pause", for: .normal)
        button.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(onTapPause), for: .touchUpInside)
        return button
    }()

    @objc func onTapPause() {
        animator.pauseAnimation()
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        animator.isInterruptible = true
        print("viewdidload page 1")
        self.view.backgroundColor = array.randomElement()
        guard let name = name else {return}
        self.view.addSubview(labelInst)
        labelInst.text = name
        labelInst.translatesAutoresizingMaskIntoConstraints = false
        labelInst.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
        labelInst.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true


        self.view.addSubview(startButton)

        startButton.topAnchor.constraint(equalTo: labelInst.topAnchor, constant: 50).isActive = true
        startButton.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true

        self.view.addSubview(pauseButton)

        NSLayoutConstraint.activate([
            pauseButton.topAnchor.constraint(equalTo: startButton.bottomAnchor, constant: 50),
            pauseButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 50)
        ])


    }



}

...