我是 iOS 编程的新手,我使用的语言是 Xcode 6.0.1 中的 Swift。我目前正在我的应用程序中实现聊天功能。我已经使用网络套接字从服务器发送/接收消息并且它工作正常。我遇到的问题是显示已发送/已接收的消息。
我创建了一个带有 TableView 、文本字段和按钮的 UIViewController 来发送消息。我已经应用了所有必要的约束来适应自动布局,并实现了所需的委托(delegate)。每次用户发送/接收消息时,都会将一个新的消息字符串添加到数据源(字符串数组)中,然后我调用:
self.tableView.reloadData
表格由带有图像的自定义单元格和 View 内的标签组成。对于一些发送/接收,它工作正常,但一段时间后,表格 View 困惑,只有自定义单元格内的图像保留,如此图所示
这是我的 cellForRowAtIndexPath 代码:
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell: customMessageCell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier ,forIndexPath: indexPath) as customMessageCell
if(messages[indexPath.row].contains("Fiona")){
cell.myAvatar.hidden = true
cell.myMessage.hidden = true
cell.myMessageBubble.hidden = true
cell.yourMessage.text = messages[indexPath.row]
cell.yourAvatar.hidden = false
}else{
cell.yourAvatar.hidden = true
cell.yourMessage.hidden = true
cell.yourMessageBubble.hidden = true
cell.myMessage.text = messages[indexPath.row]
cell.myAvatar.hidden = false
}
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
我已经检查过消息数组实际上是递增的,但是当我在 TableView 中重新加载数据时,问题出现了。我该如何解决?这是在表中插入新单元格而不是(添加到数据源+表重新加载)的更好方法吗?谢谢!
最佳答案
重用单元格时,您需要适本地完全重置属性。您的代码隐藏了消息和气泡,但没有取消隐藏它们,因此以前用于“传出”消息的单元格可能会被重新用于“传入”消息,并且消息/气泡将被隐藏。
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell: customMessageCell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier ,forIndexPath: indexPath) as customMessageCell
if(messages[indexPath.row].contains("Fiona")){
cell.myAvatar.hidden = true
cell.myMessage.hidden = true
cell.myMessageBubble.hidden = true
cell.yourMessage.text = messages[indexPath.row]
cell.yourAvatar.hidden = false
cell.yourMessageBubble.hidden = false
cell.yourMessage.hidden = false;
}else{
cell.yourAvatar.hidden = true
cell.yourMessage.hidden = true
cell.yourMessageBubble.hidden = true
cell.myMessage.text = messages[indexPath.row]
cell.myAvatar.hidden = false
cell.myMessageBubble.hidden = false
cell.myMessage.hidden = false
}
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
关于ios - swift tableview 重新加载数据问题 - 自定义单元格中缺少元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26479165/