[Xcode 实际操作]八、网络与多线程-(19)使用RunLoop使PerformSelector方法延迟动作的执行...
生活随笔
收集整理的這篇文章主要介紹了
[Xcode 实际操作]八、网络与多线程-(19)使用RunLoop使PerformSelector方法延迟动作的执行...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄:[Swift]Xcode實際操作
本文將演示使用RunLoop使PerformSelector方法延遲動作的執行。
在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】
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 }?
轉載于:https://www.cnblogs.com/strengthen/p/10069012.html
總結
以上是生活随笔為你收集整理的[Xcode 实际操作]八、网络与多线程-(19)使用RunLoop使PerformSelector方法延迟动作的执行...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习——正则化-L2
- 下一篇: “要源码上门自取”,结果人真上门了!国内