首页 > 解决方案 > 使用新的数组值立即更新前端

问题描述

我正在创建一个用户将发送消息的应用程序。我让信使工作,但是当输入新评论时,前端不会立即更新。你必须退出然后回来让它出现。

我研究了示例并从我参加的 udemy 课程中获得了代码。我尝试过使用 tableview.reload() 和 tableview.insertrows()。我正在使用 JSON 将数据发送到 PHP 和 MySQL。它立即显示在数据库中,但我的代码首先更新了 UI,它只是不工作。

让 messagetext = replyTxt.text.trimmingCharacters(in: .whitespacesAndNewlines)

    hhmessages.insert(messagetext as AnyObject, at: hhmessages.endIndex)
    let indexPath = IndexPath(row: self.hhmessages.count - 1, section: 0)

    // update tableView
    tableView.beginUpdates()

    tableView.insertRows(at: [indexPath], with: .automatic)
    tableView.endUpdates()
    // scroll to the bottom
    tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)

    // empty textView and reload it
    replyTxt.text = ""
    textViewDidChange(replyTxt)
    let recipient = messages["username"] as! String
    let rid = String(describing: messages["recipient_id"]!)
    let uuid = messages["uuid"] as! String
    puuid = UUID().uuidString

    // prepare request
    let url = URL(string: "http://localhost/messagepost.php")!
    let body = "sender_id=\(user_id)&sender=\(username)&text=\(messagetext)&recipient_id=\(rid)&recipient=\(recipient)&uuid=\(uuid)&puuid=\(puuid)"

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = body.data(using: .utf8)

代码应立即使用最新评论更新 UITableView,然后提交到数据库。我已经尝试了两天没有运气。欢迎任何帮助。

使用表源代码更新

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return hhmessages.count
}
   // Return cell to display on the tableView
// How many sections. Means numberOfSections * rows = view
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let colorSmoothGray = UIColor(red: 229/255, green: 229/255, blue: 234/255, alpha: 1)
    let colorBrandBlue = UIColor(red: 148 / 255, green: 33 / 255, blue: 147 / 255, alpha: 1)

    let pictureURL = hhmessages[indexPath.row]["uploadpath"] as? String

    // no picture in the post
    if pictureURL?.isEmpty == true {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ConversationCell
        cell.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi));

        isLoading = true

        let hhpost = hhmessages[indexPath.row]
        let smimages = hhpost["path"] as? UIImage
        let text = hhmessages[indexPath.row]["messagetext"] as! String
        cell.messageLbl.text = text
        cell.smavaImg.image = smimages

            cell.messageLbl.textAlignment = .right
            cell.messageLbl.backgroundColor = colorSmoothGray
            cell.messageLbl.textColor = .black
            cell.messageLbl.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
            cell.messageLbl.font?.withSize(25)
            cell.messageLbl.clipsToBounds = true
              // get main queue to this block of code to communicate back
   DispatchQueue.main.async {

        cell.messageLbl.sizeToFit()
        tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
        cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)

    }
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PicCell", for: indexPath) as! PicConversationCell
        cell.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi));

        cell.smavaImg.image = smimages
        //if let message = messageData {
        for i in 0 ..< self.incoming.count {
            // Confiture the constraints for cell
            if self.incoming[indexPath.row] == 1 {
                                 // Constraints
               cell.lefBubbleConstraint.isActive = true
                cell.rightBubbleConstraint.isActive = false
                if cell.postpictureImg.image == nil {
                    cell.postpictureImg.backgroundColor = colorwhite
                    cell.postpictureImg.clipsToBounds = true

                }
                else {
                    cell.postpictureImg.backgroundColor = .clear
                    cell.postpictureImg.clipsToBounds = true

                }

            }
            else if self.incoming[indexPath.row] == 0 {


                // Constraints
                cell.lefBubbleConstraint.isActive = false
                cell.rightBubbleConstraint.isActive = true
                if cell.postpictureImg.image == nil {
                    cell.postpictureImg.backgroundColor = colorwhite
                    cell.postpictureImg.clipsToBounds = true

                }
                else {
                    cell.postpictureImg.backgroundColor = .clear
                    cell.postpictureImg.clipsToBounds = true

                }

            }

        // pictures logic
        let pictureString = hhmessages[indexPath.row]["uploadpath"] as? String
        let pictureURL = URL(string: pictureString!)!

        // if there are still pictures to be loaded
        if hhmessages.count != pictures.count {

            URLSession(configuration: .default).dataTask(with: pictureURL) { (data, response, error) in
                                  // downloaded
                if let image = UIImage(data: data!) {

                    self.pictures.append(image)

                    DispatchQueue.main.async {
                        cell.postpictureImg.image = image
                    }
                }

                }.resume()

            // cached picture
        } else {

            DispatchQueue.main.async {
                cell.postpictureImg.image = self.pictures[indexPath.row]
            }
        }

        }

        return cell

    }

}

标签: iosswiftuitableview

解决方案


您是否将元素添加到您的 numberOfRowsForSection 调用中?在调用 insertRows 之前,需要更新数据源。


推荐阅读