我正在尝试在后台线程中渲染一些 View 以不影响主线程。在 Xcode 9 之前,这从来都不是问题。
DispatchQueue.global(qos: .background).async {
let customView = UIView(frame: .zero)
DispatchQueue.main.async {
self.view.addSubview(customView)
}
}
UIView.init(frame:) must be used from main thread only
这个错误出现在第二行。
更新
Apple UIView
文档实际上在线程注意事项 部分中说:
Manipulations to your application’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself, but all other manipulations should occur on the main thread.
最佳答案
Xcode 9 有一个新的运行时 Main Thread Checker 检测从后台线程调用 UIKit 并生成警告。
我知道它意味着生成警告而不会使应用程序崩溃,但您可以尝试为您的测试目标禁用 Main Thread Checker。
我在一个示例项目中尝试了这段代码,调试器在出现问题时暂停了(这是应该的),但应用程序没有崩溃。
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.global().async {
let v = UIView(frame: .zero)
}
}
关于ios - Xcode UIView.init(帧 :) must be used from main thread only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46362641/