【问题标题】:trouble with highlighting the first cell in uitableview, IOS在 uitableview,IOS 中突出显示第一个单元格的问题
【发布时间】:2017-07-10 00:21:53
【问题描述】:

我正在尝试使用以下代码突出显示我的表格视图中的第一个单元格:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        cell.layer.borderWidth = 0
        cell.layer.borderColor = nil

        cell.layer.borderWidth = 2
        cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
    }
}

一切似乎都很好。但是当我单击某个单元格时,转到另一个 viewController,然后返回我的单元格,不知何故第二个单元格已经突出显示。所以我点击了我的单元格几次,发现当我从另一个视图控制器返回到 tableview 后,下一个单元格已经突出显示(并且在 N 点击后我的所有单元格都用边框突出显示)。

我应该如何修复我的代码以仅突出显示第一个单元格,即使我转到另一个控制器并返回到我的单元格?

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    细胞被重复使用。当您为给定条件设置任何属性时,您必须始终为所有其他条件重置该属性。

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            cell.layer.borderWidth = 2
            cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
        } else {
            cell.layer.borderWidth = 0
            cell.layer.borderColor = nil
        }
    }
    

    【讨论】:

      【解决方案2】:

      您必须实现else 分支并在那里添加单元格的默认渲染。

      类似这样的:

      func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
          if indexPath.row == 0 {
              cell.layer.borderWidth = 2
              cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
          } else {
             cell.layer.borderWidth = 0
             cell.layer.borderColor = nil
          }
      }
      

      【讨论】:

        【解决方案3】:

        这段代码不应该在你的视图控制器中。创建UITableViewCell的子类...

        class myCell: UITableViewCell {
        
            var hasBorder = false {
                didSet {  
                   layer.borderWidth = hasBorder ? 2 : 0
                   layer.borderColor = hasBorder ? UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor : nil
                }
            }    
        }
        

        然后在你的cellForRow atIndexPath 方法中:

        cell.hasBorder = indexPath.row == 0
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-06
          • 2016-07-08
          • 2011-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多