我试图在一个表格视图单元格中显示每个单词,每个单词之间有2秒的停顿。这个是可能的吗?我不想不断地重新加载,修改一个单元格,然后像这样重新加载它:
var fullNameArr = message.characters.split{$0 == " "}.map(String.init)
var firstWord = true
for word in fullNameArr {
if firstWord {
firstWord = false
captionsArray.append(CaptionObject(isMacro:isMacro, number: numberToCall!.number, caption: word, time: String(describing:currentTimeInMiliseconds())))
self.reloadTableAndScroll()
} else {
let cap = self.captionsArray.last!
cap.caption = cap.caption + " " + word
captionsArray.remove(at: captionsArray.count)
captionsArray.append(cap)
self.reloadTableAndScroll()
}
self.reloadTableAndScroll()
}发布于 2017-09-22 06:29:45
您可以使用Timer来实现这一点。
要创建计时器,只需在类的顶部声明Timer变量,并在viewDidLoad方法中初始化它:
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(addWordCell), userInfo: nil, repeats: true)
// ...
}现在,每隔2秒就会调用一次addWordCell方法。顺便说一句,我建议您使用insertsRows方法,而不是一直重新加载表视图,这样效率会更高。例如,您可以像这样编写addWordCell方法:
var words = [String]()
var currentWordIndex = 0
let sentence = "Hello how are you doing today?"
func addWordCell() {
let wordsArray = sentence.components(separatedBy: " ").map({ $0 })
guard currentWordIndex < wordsArray.count else {
return
}
words.append(wordsArray[currentWordIndex])
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: words.count-1, section: 0)], with: .fade)
tableView.endUpdates()
currentWordIndex += 1
}当然,您还需要更改表视图数据源方法:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return words.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = words[indexPath.row]
return cell
}现在,如果您想在新单元格出现时添加一个漂亮的小淡入淡出效果,您可以使用willDisplayCell方法:
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.alpha = 0.0
UIView.animate(withDuration: 0.6, animations: {
cell.alpha = 1.0
})
}就这样!显然,您可以进一步改进代码,并对其进行自定义以满足您的需求,但至少这应该为您提供一个小的工作示例,说明一种可能的方法。
https://stackoverflow.com/questions/46352486
复制相似问题