立即使用新的数组值更新前端

时间:2019-04-21 02:00:46

标签: ios swift uitableview

我正在创建一个应用程序,用户可以在其中发送消息。我有Messenger正常工作,但是输入新评论时前端无法立即更新。您必须先退出,然后再回来才能显示出来。

我研究了示例,并从我上了udemy的一门课程中获得了代码。我尝试使用tableview.reload()和tableview.insertrows()。我正在使用JSON将数据发送到PHP和MySQL。它会立即显示在db中,但是我的代码首先将其更新了UI,但这只是无法正常工作。

let messagetext = replyTxt.text.trimmingCharacters(在:.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

    }

}

1 个答案:

答案 0 :(得分:0)

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