【问题标题】:cellForRow(at: indexPath) returns nil Swift3cellForRow(at: indexPath) 返回 nil Swift3
【发布时间】:2017-05-22 13:28:25
【问题描述】:

我有 UITableView 和一个自定义单元格 IconsTableViewCell 持有一个 UIImageView 和一个 UILable
如果之前选择了一行,当用户点击新行时,前一行将被取消选择,并且新行的标签文本颜色应更改。
但是,当我尝试使用 indexPath 获取对当前单元格的引用时,应用程序崩溃了。在过去的几个小时里,我一直被困在这个问题上。

class EighthViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {

let checkedImage = UIImage(named: "checked")!
let uncheckedImage = UIImage(named: "unchecked")!

struct Item {
    var name:String // name of the rows
    var selected:Bool // whether is selected or not
    var amount: Int // value of the items
}
var frequency = [
        Item(name:"Every week",selected: false, amount: 0),
        Item(name:"Every 2 weeks",selected: false, amount: 0),
        Item(name:"Every 4 weeks",selected: false, amount: 0),
        Item(name:"Once",selected: false, amount: 0),
        Item(name:"End of tenancy cleaning", selected: false, amount: 0)
    ]

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // retrieve indexPathForCellSelected from UserDefaults
   if let retrievedIndexPath = UserDefaults.standard.data(forKey: indexKey) {
    if let data1 = NSKeyedUnarchiver.unarchiveObject(with: retrievedIndexPath) as? IndexPath {
    indexPathForCellSelected = data1

 /* Inform the delegate that the row has already been selected.

      When calling 'tableView:didSelectRowAtIndexPath:', it will calculate the total amount depending on the type of cleaning:
           Weekly, End of Tenancy..etc
             Call calculateTotal() function which is using `indexPathForCellSelected`to calculate the total */
           self.tableView(self.tableView, didSelectRowAt: indexPathForCellSelected!)

  // assign the indexPath retrieved to StructS.indexPath
       StructS.indexPath = indexPathForCellSelected

      // assign StructS.price to  self.frequencyTotalPrice
                self.frequencyTotalPrice = StructS.price

            // assign self.frequencyTotalPrice to FullData.finalFrequecyAmount
                FullData.finalFrequecyAmount = self.frequencyTotalPrice

       // assign a Checkmark to the row with the corresponding indexPathForCellSelected retrieved
         tableView.cellForRow(at: indexPathForCellSelected!)?.accessoryType = .checkmark

         tableView.cellForRow(at: indexPathForCellSelected!)?.imageView?.image = checkedImage

    let cell = tableView.cellForRow(at: indexPathForCellSelected!) as! IconsTableViewCell
    cell.frequencyLabel.textColor = .black

        // assign frequency[indexPath.row].name to FullData structure
            FullData.finalFrequencyName = frequency[indexPathForCellSelected!.row].name

    //assign the row as Int value to a global var so as to determine which ViewController to unwind segue in 10th ViewController
    StructS.frequencyRowSelectedEighthVC = indexPathForCellSelected!.row
  }
 }

    // handle the selection of the row so as to update the values of labels in section header. 
   // if indexPathForCellSelected == nil, select a default type of cleaning for the first time
    if indexPathForCellSelected == nil {
        // construct an indexPath for the row we want to select when no previous row was selected ( not already saved in UserDefaults)
    let rowToSelect:IndexPath = IndexPath(row: 1, section: 0)

        // select the row at `rowToSelect` indexPath. This will just register the selectd row, However,the code that you have in tableView:didSelectRowAtIndexPath: is not yet executed because the delegate for the tablewView object in the ViewController has not been called yet. 
      self.tableView.selectRow(at: rowToSelect, animated: true, scrollPosition: UITableViewScrollPosition.none)

        // inform the delegate that the row was selected
        // stackoverflow.com/questions/24787098/programmatically-emulate-the-selection-in-uitableviewcontroller-in-swift
        self.tableView(self.tableView, didSelectRowAt: rowToSelect)

        //assign the row as Int value to a global var so as to determine which ViewController to unwind segue in 10th ViewController
        StructS.frequencyRowSelectedEighthVC = rowToSelect.row
        print("the row that was selected is\(StructS.frequencyRowSelectedEighthVC) ")
    }
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return frequency.count
}


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

   // configure the cell
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
    -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! IconsTableViewCell
        cell.frequencyLabel.text = frequency[indexPath.row].name
        cell.frequencyLabel.textColor = .gray
        cell.iconImageView.image = uncheckedImage
         return cell
    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if !frequency[indexPath.row].selected {
            // this avoid set initial value for the first time
            if let index = indexPathForCellSelected {
                // clear the previous cell
                frequency[index.row].selected = false
                tableView.cellForRow(at: index)?.accessoryType = .none
                tableView.cellForRow(at: index)?.imageView?.image = nil
            }
            //mark the new row
            frequency[indexPath.row].selected = true
            tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark

            //assign checked image to row
            tableView.cellForRow(at: indexPath)?.imageView?.image = checkedImage

            //evaluates to nil when trying to get a reference to the cell at the selected indexPath
            let cell = tableView.cellForRow(at: indexPath) as! IconsTableViewCell   
            cell.frequencyLabel.textColor = .black

            //save indexPathForCellSelected in UserDefaults
            if indexPathForCellSelected != nil { 
                // used to check if there is a selected row in the table
                let data = NSKeyedArchiver.archivedData(withRootObject: indexPathForCellSelected!)
                UserDefaults.standard.set(data, forKey: indexKey)
                self.tableView.reloadData()
            } // end of if indexPathForCellSelected
        }
    }
} //end of class

【问题讨论】:

  • 嗨,请检查链接,这可以解决您的问题.. stackoverflow.com/questions/34621076/…
  • 你是认真地打电话给tableView.cellForRow(at: indexPath) 5 次以获得始终相同的对象吗?主要问题(也是非常坏的习惯)是您将直接操作单元格(view)。 不要那样做。创建一个合适的 model,对其进行操作并重新加载 table view。
  • 尝试使用self.tableView.cellForRow(at: indexPath) as! IconsTableViewCell 获取索引路径中的单元格。
  • @vadian 你能用代码显示吗?或指向我描述您所说的内容的教程。感谢您的宝贵时间和帮助。
  • 实际上你的模型中有一个selected 属性。根据cellForRow 中的selected 进行所有设置。在didSelect 切换.selected 并重新加载表格视图。如果您只有一个部分,则只保存 UserDefaults 中的 (Int) 行,而不是使用繁琐的存档器保存整个索引路径。

标签: ios uitableview swift3 didselectrowatindexpath


【解决方案1】:
  • 创建属性selectedRow。默认选择第一行。

    var selectedRow = 0
    
  • viewWillAppear 中从 UserDefaults 中读取选定的行并重新加载表格视图

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        selectedRow = UserDefaults.standard.integer(forKey: indexKey)
        frequency[selectedRow].selected = true
        tableView.reloadData()
    }
    
  • cellForRow 中根据selected 属性设置颜色、图像和附件视图

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell" for: indexPath) as! IconsTableViewCell
        let freq = frequency[indexPath.row]
        if freq.selected {
            cell.accessoryType = .checkmark
            cell.imageView?.image = checkedImage
            cell.frequencyLabel.textColor = .gray
        } else {
            cell.accessoryType = .none
            cell.imageView?.image = uncheckedImage
            cell.frequencyLabel.textColor = .black
        }
    
        cell.frequencyLabel.text = freq.name
        return cell
    }
    
  • didSelectRowAt 中将实际索引路径与selectedRow 进行比较。如果它们不相等,则将先前选定单元格的selected 属性设置为false,将新选定单元格的属性设置为true。然后将selectedRow设置为索引路径的行,将该行保存到UserDefaults并重新加载表格视图。

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        if indexPath.row != selectedRow {
            let previousIndexPath = IndexPath(row:selectedRow, section:0)
            frequency[selectedRow].selected = false
            frequency[indexPath.row].selected = true
            selectedRow = indexPath.row   
    
            UserDefaults.standard.set(selectedRow, forKey: indexKey)
            tableView.reloadRows(at: [indexPath, previousIndexPath], with: .none)
        }
    }
    

【讨论】:

  • 点击已选择的单元格不应取消选择它。它应该没有效果。在 viewWillAppear 中,我默认选择第一行,并为其指定复选标记。然后,每当用户点击某一行时,如果该行已被选中,则不会发生任何事情。如果用户点击一个新行,前一行,它被选中,它被分配一个复选标记,前一行未被选中,它的复选标记被删除。
  • 这只是一个展示什么是可能的例子。随意删除else 分支并将最后两行放在if 范围内。但是你不需要not selected case,也可以删除相关代码。
  • 非常优雅的解决方案。你是明星
【解决方案2】:

我会试试这个(假设你有一个 Item 结构数组):

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
   let item = myItemArray[indexPath.row]
   (cell as! IconsTableViewCell).frequencyLabel.textColor = // get the color from your item selection state here
   ... // do other configurations to your cell
}

【讨论】:

  • 你知道为什么我的代码计算结果为 nil 吗?如果我打印indexPath,它会打印输出。但是,正如您在我的问题中看到的那样,此代码的计算结果为 nil 。让 cell = tableView.cellForRow(at: indexPath) 为! IconsTableViewCell
  • 就像上面已经解释的那样,您应该永远自己致电cellForRow。使用indexPath 访问您的Item,更改它,然后重新加载您的表格。
  • @Koen never 不是真的。调用 cellForRow 本身并不邪恶,我写了 ... 5 次直接操作单元格(视图)非常糟糕
猜你喜欢
  • 1970-01-01
  • 2015-09-20
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多