从后台线程在主线程中初始化 UIView

Initialising UIView in main thread from a background thread

在全局异步闭包中,我想在主线程上初始化一个 UIView。我认为这段代码可能会做到这一点,但我收到了分析器警告:

UIView.init(frame:) must by used from the main thread only.

let view: UIView = { // Line with the warning
      DispatchQueue.main.sync {
          return UIView()
      }
}()

如果您 post 更多代码,我会很有帮助,这样我们可以更好地理解上下文。 无论如何,这应该很好用:

class SomeViewController: UIViewController {

    private var customView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupCustomView()
    }

    private func setupCustomView() {
        DispatchQueue.global().async {
            /*
             1. Do some preperation / data init' on background thread.
             2. When ready, perform UI dependent initialization on main thread.
             */
            DispatchQueue.main.async {

                /* Initialize `customView` on the main queue. for example: */
                self.customView = UIView()
                self.view.addSubview(self.customView)
                self.customView.backgroundColor = .red
                self.customView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
            }
        }
    }
}

希望对您有所帮助。

尝试这样的事情:

您可以继续使用自己的实现,无需 DispatchQueue.main.sync

let view: UIView = { 
      return UIView()
}()

但是您可以随时返回主线程:

DispatchQueue.main.async {
  self.view.addSubview(view) 
}

使用.async,它给你一个独立的线程