代码之家  ›  专栏  ›  技术社区  ›  sk123

使用“发送自定义”按钮在uitableview的新行中插入数据

  •  0
  • sk123  · 技术社区  · 6 年前

    我正在使用 firebasechat . 我正在使用一个按钮并尝试使用 textfield button 发送消息。我能做到。但是,我想键入并发送消息以在我的 tableview 在聊天中。当用户键入消息时,它将在 firebase . 这只显示在 表视图 一旦我杀死并按send重新运行应用程序。我甚至更新了我的数据源,这样我就不会因为说 numbers of rows isn't equal to items inserted 不再。当我将消息附加到用户消息时,它会崩溃并给出这个消息。

    '无效更新:第0节中的行数无效。更新后现有节中包含的行数(2)必须等于更新前该节中包含的行数(0)

     var objects: [String] = []
     var userMessages = [Any]()
     var userChat:UserChat? = nil
    
     override func viewDidLoad() {
           super.viewDidLoad()
           self.objects = self.userChat!.iDs
     }
    
     @IBAction func sendButton(_ pSender: UIButton) {
            generateMessages()
        }
    
     private func generateMessages() {
            let userReference = UserReference(userID: AppDelegate.shared.user!.userID, fullName: AppDelegate.shared.user!.userName, status: .user)
            guard let stringText = textField.text else { return }
            let message = AppDelegate.shared.userMessages[stringText]
            self.conversationMessages.insert(AppDelegate.shared.addMessage(stringText, to: self.conversation!, sender:userReference, type: .text, date: message?.date), at: 0)
            let indexPath = IndexPath(row: 0, section: 0)
            self.tableView.insertRows(at: [indexPath], with: .top)
            self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
            self.tableView.reloadData()
        }
    
    func tableView(_ pTableView: UITableView, numberOfRowsInSection pSection: Int) -> Int {
            return self.userMessages.count
        }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let row = self.objectAtIndexPath(indexPath)
             let theCell = tableView.dequeueReusableCell(withIdentifier: reUseIdentifier, for: indexPath)
            return theCell
        }
    
     func objectAtIndexPath(_ indexPath: IndexPath) -> String {
            return self.objects[indexPath.row]
        }
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   vadian    6 年前

    你的代码很混乱。你有三个阵列。

    • numberOfRowsInSection 数量 userMessages 返回
    • cellForRowAt objects 使用。
    • 在中插入新消息 conversationMessages

    这就是错误的原因。使用 数组作为数据源

        2
  •  0
  •   Aljo Laurance    6 年前

    在NumberOfRowsInSection中,不要使用多个数组,而是使用单个数组例如self.userMessages。

    使用此方法更新self.userMessages

    func文本字段(文本字段:uitextfield,应在范围内更改字符:nsrange,replacementstring string:string)->bool{

        let value = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? string
    

    self.userMessages.append(值)

    返回真

    } 现在,在func textfieldshouldendediting(\textfield:uitextfield)->bool{ 返回真 }