【问题标题】:insertRowsAtIndexPaths in UITableView adding Duplicate RowsUITableView 中的 insertRowsAtIndexPaths 添加重复行
【发布时间】:2015-07-23 18:38:30
【问题描述】:

我正在使用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()

}

非常感谢!

编辑:这是cellForRowAtIndexPath 代码

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
}

【问题讨论】:

  • tableView:cellForRowAtIndexPath:的代码是什么?
  • @Larme 查看我的编辑 :)
  • 如果你 printf message.text (in sendMessage:),你有“你好”吗?能否也给一下numberOfRowInSection:numberOfSection:的代码,以防万一?
  • 顺便说一句,你可以用let cell 替换let cell:GroupChatMessageCell,因为你明确地转换了类型

标签: ios swift uitableview uiview swift2


【解决方案1】:

似乎您正在将新消息附加到数组的末尾,但在第一行插入新行。所以它要求func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell中的第一个数组元素

可以通过将self.messages.append(message) 更改为self.messages.insert(message, atIndex: 0) 来修复

【讨论】:

【解决方案2】:

实现 estimatedHeightForRowAtIndexPath 就行了!

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self tableView:tableView heightForRowAtIndexPath:indexPath];
}

享受;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多