gpt4 book ai didi

ios - 如何正确使用OperationQueue?

转载 作者:搜寻专家 更新时间:2023-11-01 07:11:00 24 4
gpt4 key购买 nike

此问题与此线程有关:how-to-set-the-height-of-a-cell-depending-on-a-uilabel-with-a-typewriter-effect

在我的 tableViewController 中,我的单元格包含 UILabel,它具有使用 setTextWithTypeAnimation 管理的打字机效果;

func configureCell(tableView: UITableView, cell: ParagraphTableViewCell, atIndexPath indexPath: IndexPath) {

let paragraph = paragraphArray[indexPath.row] as! Paragraph
cell.paragraph = paragraph

self.queue = OperationQueue()

let operation1 = BlockOperation(block: {

cell.dialogueLabel.setTextWithTypeAnimation(typedText: paragraph.dialogueLabel.text!, queue:self.queue, callBackAfterCharacterInsertion: {

self.tableView.beginUpdates()
self.tableView.endUpdates()
})

})


operation1.completionBlock = {

cell.buttonsStackViewHeightConstraint.constant = CGFloat(HEIGHT_CONSTRAINT)

UIView.animate(withDuration: 0.3, animations: {
cell.contentView.layoutIfNeeded()
}, completion: nil)

}

queue.addOperation(operation1)

}

我的打字机在 UILabel 扩展中:

extension UILabel {

func setTextWithTypeAnimation(typedText: String, queue: OperationQueue, characterInterval: TimeInterval = 0.05, callBackAfterCharacterInsertion:(()->())?) {

text = ""

for (_, character) in typedText.characters.enumerated() {

if queue.isSuspended {

OperationQueue.main.isSuspended = true
OperationQueue.main.cancelAllOperations()
break;
}

OperationQueue.main.addOperation {

self.text = self.text! + String(character)
callBackAfterCharacterInsertion?()

}

Thread.sleep(forTimeInterval: characterInterval)
}
}
}

首先,我使用 DispatchQueue 来管理单元格内的动画(参见 how-to-set-the-height-of-a-cell-depending-on-a-uilabel-with-a-typewriter-effect ),但我需要在用户关闭 View Controller 时停止线程。这就是我使用 OperationQueue 的原因(DispatchQueue 无法停止)

@IBAction func closeViewController(sender: AnyObject) {

dismiss(animated: true, completion: nil)

if self.queue != nil {

self.queue.isSuspended = true
self.queue.cancelAllOperations()
self.queue = nil
}
}

问题是调用 completionBlock 时,应用程序在我尝试更新布局约束时崩溃。

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread.

如何避免这种崩溃?

最佳答案

必须调用mainQueue 上的UI 内容。

例子:

operation1.completionBlock = {
DispatchQueue.main.async {
cell.buttonsStackViewHeightConstraint.constant = CGFloat(HEIGHT_CONSTRAINT)

UIView.animate(withDuration: 0.3, animations: {
cell.contentView.layoutIfNeeded()
}, completion: nil)
}
}

关于ios - 如何正确使用OperationQueue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44922577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com