- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
询问 unrelated question我有这样的代码: public boolean equals(Object obj) { if (this == obj) retur
在我之前的一个问题中 js: Multiple return in Ternary Operator我询问了有关使用三元运算符返回多个参数的问题。但是现在参数IsActveUser boolean(t
假设我有一个带有 return 的 if 语句。从效率的角度来看,我应该使用 if(A > B): return A+1 return A-1 或 if(A > B): return
例如考虑以下代码: int main(int argc,char *argv[]) { int *p,*q; p = (int *)malloc(sizeof(int)*10); q
PyCharm 对这段代码发出警告,说最后一个返回是不可访问的: def foo(): with open(...): return 1 return 0 如果 ope
我想实现这样的目标: 如果在返回 Json 的方法中抛出异常,则返回 new Json(new { success = false, error = "unknown"}); 但如果方法返回 View
它是多余的,但我正在学习 JS,我想知道它是如何工作的。 直接从模块返回函数 let func1 = function () { let test = function () {
我不明白我应该使用什么。我有两页 - intro.jsp(1) 和 booksList.jsp(2)。我为每一页创建了一个 Controller 类。第一页有打开第二页的按钮:
我最近在 Joomla 组件(Kunena,更准确地说是 Kunena)中看到这段代码,那么使用 $this->return VS 简单的 return 语句有什么区别. 我已经用谷歌搜索了代码,但没
我的类实现了 IEnumerable。并且可以编译这两种方式来编写 GetEnumerator 方法: public IEnumerator GetEnumerator() { yield r
我只是在编码,我想到了一个简单的想法(显然是问题),如果我有一个像这样的函数: int fun1(int p){ return(p); } 我有一个这样的函数: int fun1(int p){
这个问题在这里已经有了答案: What does the comma operator do in JavaScript? (5 个答案) 关闭 9 年前。 function makeArray
假设我写了一个 for 循环,它将输出所有数字 1 到 x: x=4 for number in xrange(1,x+1): print number, #Output: 1 2 3 4 现
我最近在这个 Apache Axis tutorial example. 中看到了下面的一段代码 int main() { int status = AXIS2_SUCCESS; ax
function a(){ return{ bb:"a" } } and function a(){ return { bb:"a" } } 这两个代码有什么区别吗,如果有请
function a() { return 1; } function b() { return(1); } 我在 Chrome 的控制台中测试了上面的代码,都返回了 1。 function c()
考虑这三个函数: def my_func1(): print "Hello World" return None def my_func2(): print "Hello World"
这可能是一个愚蠢的问题,但我正在努力,如果有一种简明的方法来测试函数的返回结果,如果它不满足条件,则返回该值(即,传递它)。。现在来回答一个可能的问题,是的,我正在寻找的类似于例外提供的东西。然而,作
我正在测试一个函数,并尝试使用 return 来做什么,并在 PowerShell 5.1 和 PwSh 7.1 中偶然发现了一个奇怪的问题,即 return cmdlet似乎不适合在团体中工作: P
这个问题已经有答案了: Return in generator together with yield (2 个回答) Why can't I use yield with return? (5 个回
我是一名优秀的程序员,十分优秀!