我有一个uitableview,对于每个单元格,我需要显示一个带换行符的字符串。我想像打字机一样显示文本,但要逐行显示:
字符串示例:
let myString="ipsum dolor sit amet \n consectetur adipiscing elit\n Vestibulum interdum felis arcu\n 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) {
}