我的 TableView 中有一些元素按某些类型排序:TypeA、TypeB 和 TypeC。
我希望当我单击带有 TypeA 的单元格时将选择颜色更改为红色,当我在 TypeB 上键入时将颜色更改为蓝色,以及在按下 TypeC 时将颜色更改为黄色。
现在我想到了这段代码:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
guard let mode = dataSource.selectedObject else {
fatalError("willDisplayCell, but no selected row?")
}
let type = ModeType(rawValue: mode.type)!
let selectionColor = UIView() as UIView
selectionColor.backgroundColor = type.color()
cell.selectedBackgroundView = selectionColor
}
我的问题是当我启动我的应用程序时调用了 willDisplayCell
而我的数据源是空的,所以我得到了一个 fatal error 。
我怎样才能克服这个问题?也许只有在调用 didSelectRowAtIndexPath
时才使用标志来执行此操作。
或者还有其他方法可以实现我的目标吗?
最佳答案
我假设您已经创建了自定义 UITableviewCell。创建单元格类型枚举。
enum CellType {
case RedCell
case Yellowcell
case OrangeCell
}
//Create enum property
class CustomCell : UITableViewCell {
var cellType:CellType = CellType.RedCell //Default is RedCell
}
现在您必须在 ViewController TableView 数据源中分配单元格类型。
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomCell
cell.cellType = .RedCell //your choice
return cell
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.cellForRowAtIndexPath(indexPath)
switch(cell.cellType) {
//Handle Switch case
case .RedCell:
cell?.contentView.backgroundColor = UIColor.redColor()
cell?.backgroundColor = UIColor.redColor()
}
}
override func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.cellForRowAtIndexPath(indexPath)
// Set unhighlighted color
cell?.contentView.backgroundColor = UIColor.blackColor()
cell?.backgroundColor = UIColor.blackColor()
}
编辑: 如果您创建了 3 种不同类型的单元格类,请检查 tableview 单元格类类型并在 didHighlightRowAtIndexPath 方法中更改颜色。
关于ios - 根据按下的单元格更改 UITableViewCell 选择颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35242257/