我有一个 collectionView
聊天,我想显示每条消息的时间。
这是 dequeueReusable
单元格函数:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! ChatMessageCollectionVIewCell
let message = messagesArray[indexPath.row]
cell.configure(with: message)
return cell
}
这是我的 collectionViewCell
文件中的配置函数
, Messages: 是NSManagedOBject
类型(核心数据),它有3个属性:usserMessage
, isFromApi
, and timeDate
.
func configure(with message:Messages)
{
messageOutlet.text = message.userMessage
viewForMessages.backgroundColor = UIColor.lightGray
let currentDateTime = Date()
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .none
timeLabel.text = formatter.string(from: currentDateTime)
if message.isFromApi == true
{
viewForMessages.backgroundColor = .lightGray
trailingConstraint.constant = 40
leadingConstraint.constant = 10
}
else
{
viewForMessages.backgroundColor = #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1)
trailingConstraint.constant = 10
leadingConstraint.constant = 40
}
}
目前它正确地显示了第一条消息的时间,但是当我在另一分钟添加另一条消息时,它也会更改第一条消息的时间。
最佳答案
您在运行时获取日期,因此对于每个单元格,它只会显示当前时间,在您的例子中是 9:58。为避免这种情况,您需要将时间存储在消息模型中。
为此尝试以下操作:
Add time property in your model,
Messages.swift
var timeString: String?
In
collectionViewCell.swift
, Update yourconfigure()
function as following:
func configure(with message: Messages) {
messageOutlet.text = message.userMessage
viewForMessages.backgroundColor = UIColor.lightGray
// Check whether time is already present in model or you need to set it as current time
if let time = message.timeString {
// time is already present in model
timeLabel.text = time
} else {
// time is not present in model, you need to set it with current time
let currentDateTime = Date()
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .none
let formattedTime = formatter.string(from: currentDateTime)
message.timeString = formattedTime // Save the time in model, for future use
timeLabel.text = formattedTime
}
if message.isFromApi == true {
viewForMessages.backgroundColor = .lightGray
trailingConstraint.constant = 40
leadingConstraint.constant = 10
} else {
viewForMessages.backgroundColor = #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1)
trailingConstraint.constant = 10
leadingConstraint.constant = 40
}
}
关于ios - collectionView 中每个单元格的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49485622/