for循环只显示数组swift中的第一项

时间:2018-04-06 20:45:53

标签: arrays swift parameter-passing

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

更新2: 以下是hhmessages数组中的参数:     发件人用户名     2.收件人     3.消息文本     4. ava image

更新:现在在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
}

1 个答案:

答案 0 :(得分: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
}