Home > OS >  Interface should be changed before time-consuming task starts in Swift
Interface should be changed before time-consuming task starts in Swift

Time:11-03

I'm trying to implement the following behaviour of collectionView cell: by tapping on the cell the appearance of the cell should be changed first! And AFTER that, a time-consuming process should start:

@objc private func addItemsToBasket(_ button: UIButton) {
         button.setTitleColor(.clear, for: .normal)
         Basket.addItems(keys: planner.currentDayKeys())
}

but unfortunately, the cell changes appearance only after the time-consuming block is finished. If I comment "Basket.addItems(keys: planner.currentDayKeys())" the cell changes its appearance prompt.

I have already tried different options in GCD, nothing helped. But actually, if I don't define a Queue the code should run line by line. Right?

It should be a very common case. Thank you in advance for any ideas.

CodePudding user response:

Like mentioned in the comments, you should not perform time consuming tasks on the main queue. GCD will definitely help you in this case. Have you tried something like this:

@objc private func addItemsToBasket(_ button: UIButton) {
    button.setTitleColor(.clear, for: .normal)
    DispatchQueue.global.async {
        Basket.addItems(keys: self.planner.currentDayKeys())
    }
}

But you need to make sure that if you do some UI changes in your Basket.addItems, you need to dispatch them back to main by wrapping them inside a DispatchQueue.main.async closure.

  • Related