cellForRow(at: indexPath) returns 由 Swift3
cellForRow(at: indexPath) returns nil Swift3
我有 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
// whosebug.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
我会试试这个(假设你有一个 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
}
创建一个属性selectedRow
。默认选择第一行。
var selectedRow = 0
在 viewWillAppear
中从 UserDefaults 中读取选定的行并重新加载 table 视图
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
设置为 true
。然后将 selectedRow
设置为索引路径的行,将行保存到 UserDefaults
并重新加载 table 视图。
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)
}
}
我有 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
// whosebug.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
我会试试这个(假设你有一个 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
}
创建一个属性
selectedRow
。默认选择第一行。var selectedRow = 0
在
viewWillAppear
中从 UserDefaults 中读取选定的行并重新加载 table 视图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
设置为true
。然后将selectedRow
设置为索引路径的行,将行保存到UserDefaults
并重新加载 table 视图。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) } }