cellForRow(at:indexPath)返回nil Swift3

时间:2017-05-22 13:28:26

标签: ios uitableview swift3 didselectrowatindexpath

我有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

2 个答案:

答案 0 :(得分: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)
        }
    }
    

答案 1 :(得分:0)

我会尝试这个(假设你有一个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
}