目錄:[Swift]Xcode實際操做html
本文將演示使用RunLoop使PerformSelector方法延遲動做的執行。swift
在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】ide
1 import UIKit 2 3 class ViewController: UIViewController { 4 5 //添加一個布爾屬性,用來標識加載狀態 6 var stillLoading = true 7 8 override func viewDidLoad() { 9 super.viewDidLoad() 10 // Do any additional setup after loading the view, typically from a nib. 11 12 //建立一個位置在(100,100),尺寸爲(100,30)的顯示區域。 13 let rect = CGRect(x: 100, y: 100, width: 100, height: 30) 14 //初始化一個標籤對象,設置標籤對象的位置和尺寸信息 15 let label = UILabel(frame: rect) 16 //設置標籤對象的顯示內容 17 label.text = "Waiting" 18 //給標籤對象設置標識值,一邊未來經過標識值,來調用標籤對象。 19 label.tag = 1 20 //將標籤對象,添加到當前視圖控制器的根視圖 21 self.view.addSubview(label) 22 23 //執行一個方法,並設置延遲執行爲0秒,即當即執行該方法 24 self.perform(#selector(ViewController.threadEvent), with: nil, afterDelay: 0.0) 25 } 26 27 //添加一個方法,用來響應定時事件 28 @objc func threadEvent() 29 { 30 //執行一個方法,並設置延遲執行爲2秒,即等待2秒後,執行該方法 31 self.perform(#selector(ViewController.workInBackground), with: nil, afterDelay: 2.0) 32 33 //添加一條while語句,這條語句將使方法一直處於執行狀態, 34 while stillLoading 35 { 36 //直到布爾變量值爲假,纔會跳出當前循環,以此實現線程等待阻塞 37 RunLoop.current.run(mode:.default, before: Date.distantFuture) 38 } 39 40 //當程序跳出當前的循環語句時,隱藏標籤對象 41 self.view.viewWithTag(1)?.isHidden = true 42 } 43 44 //添加一個方法,用來響應定時事件 45 @objc func workInBackground() 46 { 47 //將變量的值設爲否,以清除線程的阻塞 48 print(">>>>>>>>>>>>>>>>>>>") 49 stillLoading = false 50 } 51 52 override func didReceiveMemoryWarning() { 53 super.didReceiveMemoryWarning() 54 // Dispose of any resources that can be recreated. 55 } 56 }