gpt4 book ai didi

ios - cellForRow(在 : indexPath) returns nil Swift3

转载 作者:行者123 更新时间:2023-11-29 00:21:30 24 4
gpt4 key购买 nike

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

最佳答案

  • 创建属性 selectedRow。默认情况下,选择第一行。

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

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

    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 并重新加载 TableView 。

    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)
    }
    }

关于ios - cellForRow(在 : indexPath) returns nil Swift3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44114180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com