UITableView只显示1个单元格,它应显示2个单元格(Swift 3)

时间:2017-10-19 09:59:28

标签: ios swift uitableview swift3

所以我有3个单元格:SenderCellReceiverCell和默认空白Cell

我希望mainTableView显示来自发件人和收件人的所有邮件,这些邮件分别包含在messageFromCurrentUserArraymessageFromReceiverArray中。不幸的是,每当我运行下面的代码时,它只显示任一单元格。如果他们的数组不是空的,我想显示两个单元格。希望有人可以帮助我。提前谢谢!

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return allMessages.count

}

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


    if indexPath.row < messageFromCurrentUserArray.count {

        let cell = mainTableView.dequeueReusableCell(withIdentifier: "SenderCell", for: indexPath) as! SenderTableViewCell

        cell.senderMessage.text = messageFromCurrentUserArray[indexPath.row]

        mainTableView.beginUpdates()
        cell.senderMessage.sizeToFit()
        let imageFile = PFUser.current()?["profilePhoto"] as! PFFile
        imageFile.getDataInBackground(block: { (data, error) in

            if let imageData = data {

                self.currentUserImage = UIImage(data: imageData)!

            }

        })

        cell.senderProfilePhoto.image = currentUserImage
        cell.senderProfilePhoto.layer.masksToBounds = false
        cell.senderProfilePhoto.layer.cornerRadius = cell.senderProfilePhoto.frame.height / 2
        cell.senderProfilePhoto.clipsToBounds = true
        mainTableView.endUpdates()

        return cell

    } else if indexPath.row < messageFromReceiverArray.count {

        let cell = mainTableView.dequeueReusableCell(withIdentifier: "ReceiverCell", for: indexPath) as! ReceiverTableViewCell
        cell.receiverMessage.text = messageFromReceiverArray[indexPath.row]

        mainTableView.beginUpdates()
        cell.receiverMessage.sizeToFit()
        cell.receiverProfilePhoto.image = receiverImage
        cell.receiverProfilePhoto.layer.masksToBounds = false
        cell.receiverProfilePhoto.layer.cornerRadius = cell.receiverProfilePhoto.frame.height / 2
        cell.receiverProfilePhoto.clipsToBounds = true
        mainTableView.endUpdates()

        return cell

    } else {

        let cell = mainTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CellTableViewCell
        return cell
    }

}

1 个答案:

答案 0 :(得分:1)

问题是外部if语句的比较:

if indexPath.row < messageFromCurrentUserArray.count {
    //...
} else if indexPath.row < messageFromReceiverArray.count {
    // ...
} else {
    // ...
}

由于数组中的所有count都以索引0开头并且每个都停在它们的计数中,但是你的indexPath.row将达到两者的总和(例如{{1} })

您必须将第二个messageFromCurrentUserArray.count + messageFromReceiverArray.count子句和索引访问权限更改为

if