【问题标题】:for loop only shows first item in array swiftfor 循环只显示数组 swift 中的第一项
【发布时间】:2018-04-06 20:45:52
【问题描述】:

我有一个名为 loadPosts 的函数,它返回一个 Int 值数组。运行时,它在 UITableView 中使用,该 UITableView 有一个名为 setCell 的函数。仅使用数组中的第一项,然后在数组长度内重复该值。

更新 2: 以下是 hhmessages 数组中的参数: 1.发件人用户名 2. 收件人 3.留言文字 4. 头像

更新:现在在 loadPosts 函数中包含附加代码

func loadPosts()->[Int] {
    let me = user!["username"] as! String
    let uuid = messages["uuid"] as! String
    let url = URL(string: "http://localhost/message.php")!

    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    let body = "username=\(me)&uuid=\(uuid)"
    request.httpBody = body.data(using: String.Encoding.utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in

        DispatchQueue.main.async(execute: {

            if error == nil {

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    self.hhmessages.removeAll(keepingCapacity: false)
                    self.tableView.reloadData()

                    // declare new parseJSON to store json
                    guard let parseJSON = json else {
                        print("Error while parsing")
                        return
                    }

                    guard let messages = parseJSON["messages"] as? [AnyObject] else {
                        print("Error while parseJSONing")
                        return
                    }

                    self.hhmessages = messages
                    //print(self.hhmessages)

for i in 0 ..< self.hhmessages.count {
     if me == self.hhmessages[i]["senderusername"]!! as! String {
         self.incoming = [0]
 }
     if me == self.hhmessages[i]["recipient"]!! as! String {
         self.incoming = [1]
   }
}
self.tableView.reloadData()
return [Int()]
}

// UITableView

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ConversationCell

    func setCell(incoming: [Int]) {

        var layoutAttribute: NSLayoutAttribute
        var layoutConstant: CGFloat
        for i in 0 ..< self.incoming.count {

            if (self.incoming[i] == 1) {
                cell.bubbleImageView.image=#imageLiteral(resourceName: "chat_bubble_received")
            cell.messageLbl.textColor = UIColor.black
            layoutAttribute = .left
            layoutConstant = 10
            cell.contentView.addConstraint(NSLayoutConstraint(item: cell.bubbleImageView, attribute: layoutAttribute, relatedBy: .equal, toItem: cell.contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))
        }
           if (self.incoming[i] == 0) {
                cell.bubbleImageView.image = #imageLiteral(resourceName: "chat_bubble_sent")
        cell.messageLbl.textColor = UIColor.white
            layoutAttribute = .right
            layoutConstant = -10
        cell.contentView.addConstraint(NSLayoutConstraint(item: cell.bubbleImageView, attribute: layoutAttribute, relatedBy: .equal, toItem: cell.contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))

        }
        }
    }
    // get main queue to this block of code to communicate back
    DispatchQueue.main.async {

        tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
        cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
        setCell(incoming: self.incoming)

    }
    return cell
}

【问题讨论】:

  • 您的return 整数数组是否正确?您介意发布您的hhmessages 的示例吗?
  • @GIJOW 感谢您的回复。当然,我可以发布 hhmessages。我知道 hhmessages 正在工作,因为我可以看到这些消息,它们只是没有根据 setCell 中设置的条件进行格式化
  • @GIJOW 我已经包含了 hhmessages 的附加代码
  • 很抱歉造成误解,但我是指hhmessages的一些内容以了解结构
  • @NateBirkholz 谢谢内特。我非常感谢您提供的任何帮助。我很新,所以我很高兴你的回应。我通过 hhmessages.count 确定行数。 hhmessages 保存数组值。这有意义吗?

标签: arrays swift parameter-passing


【解决方案1】:
func loadPosts()->[Int] {
    let me = user!["username"] as! String
    let uuid = messages["uuid"] as! String
    let url = URL(string: "http://localhost/message.php")!

    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    let body = "username=\(me)&uuid=\(uuid)"
    request.httpBody = body.data(using: String.Encoding.utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in

        DispatchQueue.main.async(execute: {

            if error == nil {

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    self.hhmessages.removeAll(keepingCapacity: false)
                    self.tableView.reloadData()

                    // declare new parseJSON to store json
                    guard let parseJSON = json else {
                        print("Error while parsing")
                        return
                    }

                    guard let messages = parseJSON["messages"] as? [AnyObject] else {
                        print("Error while parseJSONing")
                        return
                }

                    self.hhmessages = messages
                    //print(self.hhmessages)

                    /// This is the part I edited
                    for i in 0 ..< self.hhmessages.count {
                        if me == self.hhmessages[i]["senderusername"]!! as! String {
                            self.incoming.append(0)
                        }
                        if me == self.hhmessages[i]["recipient"]!! as! String {
                            self.incoming.append(1)
                        }
                    }
                    self.tableView.reloadData()
                    return [Int()]
 }

更改您的cellForRowAt 以使用indexPath.row 作为self.incoming 的索引:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ConversationCell

    func setCell(incoming: [Int]) {

        var layoutAttribute: NSLayoutAttribute
        var layoutConstant: CGFloat

        if (self.incoming[indexPath.row] == 1) {
            cell.bubbleImageView.image=#imageLiteral(resourceName: "chat_bubble_received")
            cell.messageLbl.textColor = UIColor.black
            layoutAttribute = .left
            layoutConstant = 10
            cell.contentView.addConstraint(NSLayoutConstraint(item: cell.bubbleImageView, attribute: layoutAttribute, relatedBy: .equal, toItem: cell.contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))
        }
        if (self.incoming[indexPath.row] == 0) {
            cell.bubbleImageView.image = #imageLiteral(resourceName: "chat_bubble_sent")
            cell.messageLbl.textColor = UIColor.white
            layoutAttribute = .right
            layoutConstant = -10
            cell.contentView.addConstraint(NSLayoutConstraint(item: cell.bubbleImageView, attribute: layoutAttribute, relatedBy: .equal, toItem: cell.contentView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant))

        }
    }
// get main queue to this block of code to communicate back
    DispatchQueue.main.async {

        tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
        cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
        setCell(incoming: self.incoming)

    }
    return cell
}

【讨论】:

  • 非常感谢您对我的帮助。我检查了结果。 hhmessages 有 54 行(消息),根据数据总共 7 次传入应为 1,其余为 0。我采纳了你很棒的建议,但它导致了一个循环 54 次的 1 和 0 序列。条件格式仍然没有通过。就好像第一个“传入”进入格式化条件,但没有其他。有意义吗?
  • @techgirl 我很困惑。您的布局代码看起来应该可以工作了!我将尝试根据我目前所知道的重新创建您的项目。不过,这应该需要一点时间。 :)
  • 我很抱歉造成混乱。 :(
  • @techgirl 想通了,我应该早点看到它,我很傻。查看修改后的答案
  • 成功了。你才是真正的MVP。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多