我有一个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发布于 2017-05-22 14:49:39
selectedRow。默认情况下,将选择第一行。
变量selectedRow =0viewWillAppear中,从UserDefaults读取选定的行并重新加载表视图
重写func viewWillAppear(_动画: Bool) {super.viewWillAppear(动画) selectedRow = UserDefaults.standard.integer(forKey: indexKey) frequencyselectedRow.selected = true tableView.reloadData() }cellForRow中,根据selected属性设置颜色、图像和附件视图
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier:"Cell“for: indexPath) as!IconsTableViewCell设freq = frequencyindexPath.row如果freq.selected { cell.accessoryType = .checkmark cell.imageView?.image = checkedImage cell.frequencyLabel.textColor = .gray } if { cell.accessoryType = .none cell.frequencyLabel.textColor = uncheckedImage cell.frequencyLabel.textColor= .black } cell.frequencyLabel.text = freq.name返回单元}didSelectRowAt中,比较实际的索引路径和selectedRow。如果它们不相等,则将前一个选定单元格的selected属性设置为false,将新选定的单元格设置为true。然后将selectedRow设置为索引路径的行,将该行保存为UserDefaults并重新加载表视图。
func tableView(_ tableView: UITableView,didSelectRowAt indexPath : IndexPath) { if indexPath.row != selectedRow { let previousIndexPath =IndexPath(行: selectedRow,节:0) frequencyselectedRow.selected = false frequencyindexPath.row.selected = true selectedRow= indexPath.row UserDefaults.standard.set(selectedRow,forKey: UserDefaults.standard.set)(at:,,with:)}}发布于 2017-05-22 13:55:37
我会尝试这样做(假设您有一个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
}https://stackoverflow.com/questions/44114180
复制相似问题