ios - 根据按下的单元格更改 UITableViewCell 选择颜色

标签 ios swift tableview

我的 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/

相关文章:

javascript - 在 UIWebView 上定义事件

ios - 更改拉动刷新事件指示器

xcode - 尝试从查询中将 Parse PFFiles 加载到 UITableView

ios - 将数据从 xib 单元格传递到 View Controller

ios - 在 Facebook 上分享,手机上不显示文字。 ( swift )

ios - 从一个 View Controller 向另一个 View Controller 发出委托(delegate)调用

iphone - UITableViewCell 中弃用的警告消息

ios - 如何在相册上选择图像 - iOS 测试 KIF

ios - 当 UITableViewCell 在两个单元格背景颜色之间设置动画时,为什么我不能点击它?

ios - 我无法向我的应用发送 Firebase Cloud Messaging 推送通知我按照步骤操作但无处可去