用于在 UITableViewCell 中逐行显示字符串的动画



我有一个UITableView,对于每个单元格,我需要显示一个带有换行符的字符串。我想像打字机一样显示文本,但逐行显示:

  • 显示一行。
  • 等待几秒钟。
  • 显示第二行。
  • 等几秒钟...

字符串示例:

let myString="ipsum dolor sit amet n consectetur adipiscing elitn Vestibulum interdum felis arcun quis iaculis dolor malesuada ut"

法典:

class ViewController:UIViewController, UITableViewDataSource, UITableViewDelegate
@IBOutlet var tableView : UITableView!
var queue:OperationQueue!
func configureCell(tableView: UITableView, cell: WithButtonsTableViewCell, atIndexPath indexPath: IndexPath) {
self.queue = OperationQueue()
cell.dialogueLabel.setTextWriting(typedText: myString,callBackAfterCharacterInsertion: {
self.tableView.beginUpdates()
self.tableView.endUpdates()
})
cell.dialogueLabel.operation1.completionBlock = {
//DO STUFF when all lines have been displayed
}
}
}

//Custom class for UILabel in the cell 
class TypeWriterLabel: UILabel {
var queue:OperationQueue!
var operation1:BlockOperation! 
func setTextWriting(typedText: String, callBackAfterCharacterInsertion:(()->())?) {
text = ""
let delimiter = "n"
let lines = typedText.components(separatedBy: delimiter)
self.queue = OperationQueue()
self.operation1 = BlockOperation(block: {
for lineItem in lines {
if self.queue != nil {
OperationQueue.main.addOperation({
self.text = self.text! + lineItem + "n"
self.attributedText = self.setAttributedStyle()
callBackAfterCharacterInsertion?()
})
}
}
})
self.queue.addOperation(self.operation1)
}
}

使用此代码,所有文本一次性显示在一个块中。 我想我应该在每个换行符之间添加一个延迟时间,所以我试图在很多地方添加一个 asyncAfter,但没有成功。

DispatchQueue.main.asyncAfter(deadline: .now() + 1) { 
}

我分享我的解决方案。

func writingTextAnimation(dialogueLabelCell:UILabel, text:String, completion:@escaping ()->()) {
let delimiter = "n"
var lines = text.components(separatedBy: delimiter)
var index = 0
animationTimer = Timer.scheduledTimer(withTimeInterval: TYPING_TIME_INTERVAL, repeats: true, block: { (timer: Timer) in
if index < lines.count {
dialogueLabelCell.text =  dialogueLabelCell.text! + lines[index] + delimiter
self.tableView.beginUpdates()
self.tableView.endUpdates()
index = index + 1
} else {
self.animationTimer?.invalidate()
self.animationTimer = nil
completion()
}
})
}

最新更新