我在tableView单元格中有一个UILabel,我想逐行设置动画。字符串带有\n
的换行符,并且lines.count
按预期返回7,但是即使字符串本身不是nil,也没有将任何行添加到标签。
cellForRow中的代码
var index = 0
let lines = messageList[indexPath.row].message.components(separatedBy: "\n")
senderCell.otherUserMessage.numberOfLines = lines.count
Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { [weak self] timer in
if index != lines.count {
let char = lines[index]
let nChar = "\n\(char)"
senderCell.otherUserMessage.text! += nChar
print("char is \(nChar)") //nChar prints the proper text
print("senderCellText is \(senderCell.otherUserMessage.text!)") // but this prints an array of numbers
// Play sound each time
do {
self!.audioPlayer = try AVAudioPlayer(contentsOf: self!.koalaMessageSound)
self!.audioPlayer.play()
}catch{
// couldn't load file :(
}
index += 1
} else {
timer.invalidate()
}
})
我发现要为Label设置动画的唯一方法是: 1.为原始标签中的每一行创建一个标签副本(计算frame.height / lineHeight) 2.用矩形遮盖每个副本的每一行 3.分别为每个Label
设置动画-每个标签仅在此处显示一行,因此您可以分别控制它们。
注意:使用\n
是不可能的,因为有时在较小的设备上,由于文本的长度,文本可能会转到下一行,因此,要获得实际的行数,您需要像我在第1点所描述的那样进行计算。