swift--Timer实现定时器功能,每个一段时间执行具体函数,可以重复,也可以只执行一次

阅读 41

2023-08-22

1,创建

//控制器
        timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(FifteenthViewController.tickDown), userInfo: nil, repeats: true)

2,方法实现

func tickDown()
{
        let a = Int(arc4random()%255)+1
        let b = Int(arc4random()%255)+1
        let c = Int(arc4random()%255)+1
        self.view.backgroundColor = UIColor.init(red: CGFloat(a/255), green: CGFloat(b/255), blue: CGFloat(c/255), alpha: 1.0)    
}

3,终止定时器的方法

timer.invalidate()



精彩评论(0)

0 0 举报