簡體   English   中英

調用出隊單元時出隊可重用單元崩潰

[英]Dequeue Reusable Cell crashes when calling dequeued cell

我正在嘗試使用一個列出多個內容的表格視圖,並允許用戶瀏覽並選擇帶有復選框的多個單元格。 我的代碼可以工作到一定程度,問題是應用程序崩潰並出現以下錯誤

致命錯誤:展開一個可選值時意外發現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!

經過大約一天的實驗,我還沒有弄清楚實際的問題(除了觀察到的似乎是關於調用出隊單元格的觀察)

任何幫助表示贊賞。

當這條線

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

崩潰意味着您訪問的是非可見單元,因此無論使用

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

或更好地使用表的dataSource數組從單元格中獲取要錯誤地處理的數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM