我正在創建一個UIView
,它在UIViewController
中運行許多異步任務。在某些時候,我希望能夠刪除UIView
並停止所有正在運行的任務。但是,調用removeFromSuperview()
不會停止任務。有沒有辦法可以做到這一點?停止UIView中的所有異步任務
示例代碼
class ViewController: UIViewController {
let v = SomeView()
override func viewDidLoad() {
super.viewDidLoad()
v.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
self.view.addSubview(v)
let v1 = UIButton()
v1.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
v1.backgroundColor = UIColor.blue
v1.addTarget(self, action: #selector(removeV(_:)), for: .touchUpInside)
self.view.addSubview(v1)
}
func removeV(_ sender: UIButton) {
print("V REMOVED")
v.removeFromSuperview()
}
}
class SomeView: UIView {
override func draw(_ rect: CGRect) {
DispatchQueue.global().async {
var c = 0
while true {
print(String(c) + " DOING SOME TASK")
c += 1
sleep(1)
}
}
}
}
示例記錄
0 DOING SOME TASK
1 DOING SOME TASK
V REMOVED
2 DOING SOME TASK
3 DOING SOME TASK
4 DOING SOME TASK
...
這是一個例子來說明一些任務正在發生很長一段時間。當我刪除視圖時,我希望所有這些任務都停止。 –