1. 程式人生 > >[Swift4.2互動教程]八、實用進階-(3)閉包在定時任務、動畫和執行緒中的使用

[Swift4.2互動教程]八、實用進階-(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,width: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,width: 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 }