ios - 调用出队单元格时出队可重用单元格崩溃

标签 ios swift uitableview tableview

我正在尝试创建一个表格 View ,其中列出多个内容并允许用户浏览并选择带有复选框的多个单元格。我的代码一直运行到某一点,问题是应用程序崩溃并出现以下错误

Fatal error: Unexpectedly found nil while unwrapping an Optional value

每当我调用下面的代码

swift 让 currentCell = recommendToFriendTableView.cellForRow(at: selectedRow[i]) 作为? 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 调用不在 View (也称为出队)的单元格上

  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!

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

感谢任何帮助。

最佳答案

当这条线

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

崩溃,这意味着你访问了一个不可见的单元格,所以要么使用

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

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

关于ios - 调用出队单元格时出队可重用单元格崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56078810/

相关文章:

ios - 为什么 App 名称更改没有反射(reflect)在 iOS 7 通知中心?

ios - 如何将多个节点添加到场景并一次移动所有节点。 swift 。 SpriteKit

ios - Crashlytics 日志中没有自动跟踪的屏幕。只有自定义事件可见

ios - 移除 UITableView 的边框,而不是分隔符

ios - 如何从 Swift 打开邮件应用程序

ios - 调用 popViewController 时内存未释放

ios - 具有基本身份验证挑战的 NSURLSession

Swift 3 转换类型别名闭包转换问题

ios - 在 UITableViewCell 中扩展 UITextView 高度(查看更多效果)

ios - 如何在 UITableView 中更改基于索引的部分通用颜色