【问题标题】:Dequeue Reusable Cell crashes when calling dequeued cell调用出列单元时出列可重用单元崩溃
【发布时间】:2023-04-01 10:57:02
【问题描述】:

我正在尝试创建一个表格视图,其中列出了多项内容,并允许用户通过复选框选择多个单元格。我的代码一直工作到某个点,问题是应用程序崩溃并出现以下错误

致命错误:在展开可选值时意外发现 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!

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

感谢任何帮助。

【问题讨论】:

  • 检查您的手机插座
  • 我曾经遇到过类似的问题,并通过使用来自底层数据源而不是单元格的数据来解决它。不确定您是否可以使用这种方法。
  • 哪个变量为零,在哪一行?你为什么要直接打电话给cellForRowAt?无论您在调用 cellForRowAt 时尝试做什么,都可以在不调用该函数的情况下更好地重写。
  • @matt selectedRow 在所示的第二个代码块中定义。它是recommendToFriendTableView.indexPathsForSelectedRows,其中RecommendToFriendTableView 是一个UITableView
  • 运行此代码时您的内容可能会滚动?

标签: ios swift uitableview tableview


【解决方案1】:

当这条线

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多