Getting a “This application is modifying the autolayout engine from a background thread” error?

后端 未结 21 1852
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 15:52

Been encountering this error a lot in my OS X using swift:

\"This application is modifying the autolayout engine from a background thread, which can

21条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 16:38

    When you try to update a text field value or adding a subview inside a background thread, you can get this problem. For that reason, you should put this kind of code in the main thread.

    You need to wrap methods that call UI updates with dispatch_asynch to get the main queue. For example:

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
       self.friendLabel.text = "You are following \(friendCount) accounts"
    })
    

    EDITED - SWIFT 3:

    Now, we can do that following the next code:

    // Move to a background thread to do some long running work
    DispatchQueue.global(qos: .userInitiated).async {
       // Do long running task here
       // Bounce back to the main thread to update the UI
       DispatchQueue.main.async {
          self.friendLabel.text = "You are following \(friendCount) accounts"
       }
    }
    

提交回复
热议问题