首页 > 解决方案 > 在 swift4 中使用 NSTimer 处理 UIPagecontrol

问题描述

我正在尝试添加NSTimer用于图像滑动的 UIPagecontrol。但无法得到它。我已经尝试了下面给出的东西。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var pagecontrol: UIPageControl!
    @IBOutlet weak var imgview: UIImageView!

     var tTime: Timer!
     var index = 0
     var items = ["1.png","11.png","111.png","1111.png"]

    override func viewDidLoad() {
        super.viewDidLoad()
        configurePageControl()
        let timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
        // Do any additional setup after loading the view, typically from a nib.
    }

    func configurePageControl() {
        self.pagecontrol.numberOfPages = items.count
        self.pagecontrol.currentPage = 0
        self.pagecontrol.tintColor = UIColor.red
        self.pagecontrol.pageIndicatorTintColor = UIColor.black
        self.pagecontrol.currentPageIndicatorTintColor = UIColor.green
    }

    @objc func update()  {
        index = index + 1
    }
}

如果有人提供帮助,那就太好了。提前致谢。

标签: iosswiftnstimeruipagecontrol

解决方案


改变你的

@objc func update()  {
        index = index + 1

    }

作用于

@objc func update()  {
    index = index + 1

    if index >= items.count {
        index = 0
    }
    imgview.image = UIImage(named: items[index])
    pagecontrol.currentPage = index
}

它应该工作。


推荐阅读