我是iOS编程的新手,我使用的语言是Xcode 6.0.1中的Swift。我目前正在我的应用程序中实现聊天功能。我使用Web套接字从服务器发送/接收消息,它工作正常。我遇到的问题是显示发送/接收的消息。
我创建了一个带有表视图,文本字段和按钮的UIViewController来发送消息。我已经应用了所有必要的约束来适应自动布局,并实现了所需的委托。每次用户发送/接收消息时,都会向数据源(字符串数组)添加一个新的消息字符串,然后我调用:
self.tableView.reloadData
该表由自定义单元格组成,其中包含图像和视图内的标签。它可以在一些发送/接收时正常工作,但过了一段时间后,表视图会混乱并且只保留自定义单元格内的图像,如此图
这是我的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
}
我已经检查过消息数组实际上正在递增,但是当我在表视图中重新加载数据时,会出现问题。我该如何解决?这是在表中插入新单元格而不是(添加到数据源+表重新加载)的更好方法吗?谢谢!
答案 0 :(得分:5)
重复使用单元格时,需要完全重置属性。您的代码会隐藏消息和气泡,但不会取消隐藏它们,因此以前用于“传出”消息的单元格可能会被重复用于“传入”消息,并且消息/气泡将被隐藏。
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
}