我当前可以单击多行并更改标签的颜色,然后转到下一个视图控制器,但当我回到表视图时,我将在视图中打印selectrowatindexpath并显示正确的值,但是标签没有着色。选择表示标签是白色的,但即使打印选定的值,标签也不是。我该如何解决这个问题?
var selected = ["dog", "cat", "bat"]
var animal = [String]() //selected data
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: selectcell = table.dequeueReusableCellWithIdentifier("Cell") as! selectcell
cell.subjecters.text = selected[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.None
if(animal != []){
for(var i = 0; i < selected.count; i++){
for(var x = 0; x < animal.count; x++){
if(selected[i] == animal[x]){
var rowtoselect = NSIndexPath(forRow: i, inSection: 0)
self.table.selectRowAtIndexPath(rowtoselect, animated: true, scrollPosition: .None)
cell.subject.textColor = UIColorFromRGB("f07763")
}
}
}
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCell = table.cellForRowAtIndexPath(indexPath) as! selectcell
currentCell.subject.textColor = UIColorFromRGB("ffffff")
currentCell.selectionStyle = UITableViewCellSelectionStyle.None
self.selected.append(currentCell.subjecter.text!)
}
答案 0 :(得分:0)
您正在更新didSelectRowAtIndexPath
func中的标签,但只有在您进行选择时才会调用。
当您返回视图时,单元格会通过cellForRowAtIndexPath
更新 - 因此请更改颜色
答案 1 :(得分:0)
将您的模型(动物数组)扩展为具有属性name
和selected
的类。在cellForRowAtIndexPath
中设置颜色取决于selected
属性并删除selectRow....
选择行后获取该行的模型项,将selected
设置为true
并重新加载表视图。这是实用的MVC。
class Animal {
let name : String
var selected = false
init(name : String) {
self.name = name
}
}
class ViewController : UITableViewController {
var animals = [Animal]()
override func viewDidLoad() {
animals = [Animal(name: "dog"), Animal(name: "cat"), Animal(name: "bat")]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animals.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: selectcell = table.dequeueReusableCellWithIdentifier("Cell") as! selectcell
cell.selectionStyle = UITableViewCellSelectionStyle.None
let animal = animals[indexPath.row]
cell.subjecters.text = animal.name
cell.subject.textColor = animal.selected ? UIColorFromRGB("ffffff") : UIColorFromRGB("f07763")
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let animal = animals[indexPath.row]
animal.selected = true
tableView.reloadData()
}
}