我正在使用 insertRowsAtIndexPaths
方法将新行添加到我的 UITableView
。存在添加重复行的问题。
例如,如果我键入 "HI"
,然后触摸回车,则会向表格中添加包含文本 "HI"
的行。如果我然后返回并键入 "Hello"
并按回车键,则会再次添加显示 "HI"
的行。这是一些代码:
func textFieldShouldReturn(textField: UITextField) -> Bool {
sendMessage(textField.text)
return true
}
func sendMessage(text:String){
var message = Message(text: text)
//global array that stores all the messages
self.messages.append(message)
let indexPathZero : NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(NSArray(object: indexPathZero) as [AnyObject], withRowAnimation: UITableViewRowAnimation.None)
self.tableView.endUpdates()
}
非常感谢!
Edit: Here's the
cellForRowAtIndexPath
code
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:GroupChatMessageCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! GroupChatMessageCell
cell.message.text = messages[indexPath.row].text
cell.contentView.transform = CGAffineTransformMakeScale (1,-1);
return cell
}
最佳答案
您似乎将新消息附加到数组的末尾,但在第一行插入了新行。所以它在 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
可以通过将 self.messages.append(message)
更改为 self.messages.insert(message, atIndex: 0)
来修复
关于ios - UITableView 中的 insertRowsAtIndexPaths 添加重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31595525/