[Swift实际操作]八、实用进阶-(3)闭包在定时任务、动画和线程中的使用实际操作

闭包的使用相当广泛,它是可以在代码中被传递和引用的具有独立功能的模块。
双击打开之前创建的空白项目。
本文将演示闭包在定时任务、动画和线程中的使用。
在左侧的项目导航区,打开视图控制器的代码文件:ViewController.swift

一、闭包在定时器中的用法

 1 import UIKit
 2 class ViewController: UIViewController{
 3 
 4   override func viewDidLoad(){
 5     super.viewDidLoad()
 6 //Do any additional setup after loading the view, typically from a nib.
 7 //创建一个定时器,每隔1秒钟循环执行位于后方的闭包语句中的代码。
 8     Timer.scheduledTimer(withTimeInterval: 1.0,repeats: true)
 9     {
10         (timer: Timer) in print("Timer action...")
11      }
12   }
13 
14    override func didReceiveMemoryWarning(){
15      super.didReceiveMemoryWarning()
16      //Dispose of any resources that can be recreated.
17 
18    }
19 }

二、闭包在动画中的用法

 1 import UIKit
 2 class ViewController: UIViewController{
 3 
 4 //首先给当前的类添加一个视图类型的属性
 5   var animationView: UIView 
 6 
 7   override func viewDidLoad(){
 8     super.viewDidLoad()
 9 //Do any additional setup after loading the view, typically from a nib.
10 //对视图属性进行初始化,设置它的显示区域
11     animationView = UIView(frame: CGRect(x: 0,y: 40,50,height: 50))
12 //设置视图的背景颜色为橙色
13     animationView.backgroundColor = .orange
14 //将视图添加到当前视图控制器的根视图
15     self.veiw.addSubview(animationView)
16 //调用视图类的方法,创建一个时长为1秒的动画
17     UIView.animate(withDuration: 1.0,animations: {
18 //通过修改视图对象的显示区域属性,在1秒钟的时间里,将视图向右侧移动200点的距离
19     self.animationView.frame = CGRect(x: 200,y: 40, 50,height: 50)
20      }){(end:Bool) in 
21 //动画结束后,在控制台输出一条日志语句。
22           print("Animation done.")      
23        }
24   }
25 
26    override func didReceiveMemoryWarning(){
27      super.didReceiveMemoryWarning()
28      //Dispose of any resources that can be recreated.
29 
30    }
31 }

三、闭包在线程中的用法

 1 import UIKit
 2 class ViewController: UIViewController{
 3 
 4   override func viewDidLoad(){
 5     super.viewDidLoad()
 6 //Do any additional setup after loading the view, typically from a nib.
 7 
 8 //方式1:分离一个新的线程,并在新的线程中执行闭包语句中的任务
 9     Thread.detachNewThread{
10         print("Do something on a new thread.")
11      }
12 
13 //方式2:在调度队列中,异步执行闭包语句中的任务
14      DispatchQueue.main.async{
15         print("DispatchQueue.main.async")
16      }
17 
18 //方式3:在等待两秒钟之后,异步执行闭包语句中的任务。
19      DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0){
20          print("DispatchQueue.main.asyncAfter")
21      }
22     }
23 
24    override func didReceiveMemoryWarning(){
25      super.didReceiveMemoryWarning()
26      //Dispose of any resources that can be recreated.
27 
28    }
29 }
原文地址:https://www.cnblogs.com/strengthen/p/9808527.html