调用出队单元时出队可重用单元崩溃

时间:2019-05-10 13:34:44

标签: ios swift uitableview tableview

我正在尝试使用一个列出多个内容的表格视图,并允许用户浏览并选择带有复选框的多个单元格。我的代码工作到一定程度,问题是应用程序崩溃并出现以下错误

  

致命错误:解开可选值时意外发现nil

每当我调用以下代码

swift let currentCell = recommendToFriendTableView.cellForRow(at: selectedRow[i]) as? RecommendToFriendsTableViewCell

这是我们设置单元格的方法

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (tableView == self.friendListTableView) {


            let cell:  FriendListTableViewCell = tableView.dequeueReusableCell(withIdentifier: "FriendListCell") as! FriendListTableViewCell

            let rowNumber = (indexPath as NSIndexPath).row
            var name = ""
            if searchActive {
                name = filtered[rowNumber]
            }
            else {
                name = names[rowNumber]
            }
            cell.friendNameLabel.text = name
            cell.friendNameLabel.backgroundColor = tableViewBgColor
            cell.friendNameLabel.textColor = textColor
            cell.recommendToFriendButton.layer.borderWidth = 1
            cell.recommendToFriendButton.layer.borderColor = tableViewBgColor.cgColor
            cell.recommendToFriendButton.layer.cornerRadius = 6
            cell.recommendToFriendButton.backgroundColor = buttonBgColor
            cell.backgroundColor = tableViewBgColor
            //set target for buttons
            cell.recommendToFriendButton.tag = rowNumber
            cell.recommendToFriendButton.addTarget(self, action:#selector(recommendToFriendButtonClicked), for: UIControl.Event.touchUpInside)

            return cell
        }
        else {
            let cell: RecommendToFriendsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RecommendToFriendsCell") as! RecommendToFriendsTableViewCell
            let rowNumber = (indexPath as NSIndexPath).row
            // set the content view background color
            cell.contentView.backgroundColor = tableViewBgColor
            // set the text color
            cell.nameLabel.textColor = textColor
            var dict_friend = NSMutableDictionary()
            if searchActive {
                dict_friend = filteredFriendsArray[rowNumber]
            }
            else {
                dict_friend = friendsArray[rowNumber]
            }

            let name = dict_friend["name"] as! String
            cell.nameLabel.text = name
            let friendUID = dict_friend["uid"] as! String
            cell.friendID = friendUID
            let imageAddress = dict_friend["photo"] as? String

            if imageAddress != "unavailable" && imageAddress != nil && imageAddress != ""{



                //Swift forces us to wrap strings as optional to use them in logic
                if let imageURL = imageAddress as String? {

                    //Swift forces us to wrap strings as optional to use them in logic
                    if let image = imageURL as String? {

                        //We convert the string into a URL and get the image
                        let url = URL(string: image)
                        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

                            if error != nil {
                                print(error!)
                                return
                            }

                            //We create a new async thread to download and update the image
                            DispatchQueue.main.async {
                                //imageView.image = UIImage(data: data!)
                                cell.photoImageView.image = UIImage(data:data!)

                            }
                        }).resume()
                    }



                } else {
                    cell.photoImageView!.image = UIImage(named: "placeholder-profile-male.png")
                }

            } else {
                cell.photoImageView!.image = UIImage(named: "placeholder-profile-male.png")
            }

            cell.checkBoxImageView.image = cell.checkBoxImageView.image!.withRenderingMode(.alwaysTemplate)
            cell.checkBoxImageView.tintColor = textColor
            // Style the profile photo to show in a circle
            cell.photoImageView.layer.borderWidth = 0
            cell.photoImageView.layer.borderColor = tableViewBgColor.cgColor
            // Set cornerRadius = a square UIImageView frame size width / 2
            // In our case, UIImageView height = width = 60 points
            cell.photoImageView.layer.cornerRadius = 30
            cell.photoImageView.clipsToBounds = true
            cell.selectionStyle = .none // to prevent cells from being "highlighted"
            return cell
        }
    }

这是我们与他们互动的方法。崩溃发生在cellForRow调用中,该调用导致视线不在视线范围内(又出队)

  var firstFriendName: String = ""
        var numberOfFriends = 0
        if let selectedRow = recommendToFriendTableView.indexPathsForSelectedRows {
            numberOfFriends = selectedRow.count
            for i in 0..<selectedRow.count {
                let currentCell = recommendToFriendTableView.cellForRow(at: selectedRow[i]) as! RecommendToFriendsTableViewCell
                let friendID = currentCell.friendID
                idList.append(",\(friendID)")
            }
            let firstSelectedCell = recommendToFriendTableView.cellForRow(at: selectedRow[0]) as! RecommendToFriendsTableViewCell
            firstFriendName = firstSelectedCell.nameLabel.text!

经过大约一天的实验,我还没有弄清楚实际的问题(除了观察到的问题似乎与调用出队的细胞有关)

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

此行时

 let currentCell = recommendToFriendTableView.cellForRow(at: selectedRow[i]) as! RecommendToFriendsTableViewCell

崩溃意味着您访问的是不可见的单元格,因此请使用

 if let currentCell = recommendToFriendTableView.cellForRow(at: selectedRow[i]) as? RecommendToFriendsTableViewCell { }

或更好地使用表的dataSource数组从单元格中获取要错误地处理的数据