ios - Xcode UIView.init(帧 :) must be used from main thread only

标签 ios swift xcode multithreading uikit

我正在尝试在后台线程中渲染一些 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。

enter image description here

我在一个示例项目中尝试了这段代码,调试器在出现问题时暂停了(这是应该的),但应用程序没有崩溃。

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/

相关文章:

ios - 如何在 iOS6 中更改 UITextfield 光标颜色

ios - parentViewController 和presentingViewController 都为零

swift - 拖放同一 Sprite 的子级

ios - 返回后重新加载 UITableview

swift - 单击第二个选项卡时选项卡栏不起作用

objective-c - Core Data (Mac) 如何在 ID 字段上实现自增

iphone - 获取当前用户位置的地址

javascript - 如何在 swift 4 的 WKWebView 中从网页中删除 DIV 标签?

ios - 照片库和媒体库之间的区别

ios - Pod 的资源目标错误地需要设置 Swift 版本