【问题标题】:How to add a border to a cell upon clicking单击时如何为单元格添加边框
【发布时间】:2016-07-29 07:45:40
【问题描述】:

我的目标是在用户单击单元格时制作边框。

以下代码有效:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("Cell \(indexPath.row) selected")
}

然后我添加了这段代码以使边框着色但没有效果。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let cell : MKStandItemAdd = collectionView.dequeueReusableCellWithReuseIdentifier("ItemCell", forIndexPath: indexPath) as! MKStandItemAdd
    cell.layer.borderWidth = 7
    cell.layer.borderColor = UIColor.blueColor().CGColor
    print("Cell \(indexPath.row) selected")
}

上面这段代码仍然可以打印,但没有改变颜色。

所以我补充说:

self.collectionView.reloadData()

但现在什么都没有发生。它不再打印,也不会重新加载集合。

【问题讨论】:

  • 不要调用 reloadData()。重新加载特定单元格。
  • 当您单击单元格时.. 存储该索引,然后根据索引在cellForItemAtIndexPath 方法中创建边框
  • 尝试添加cell.layer.masksToBounds = YES;

标签: ios swift xcode uicollectionview


【解决方案1】:

当您重新加载或滚动单元格时,didSelectItemAtIndexPath 上的直接设置为单元格将不会出现。

更好的方法是在您的cellForRowAtIndexPath 中呈现单元格。

首先,我们需要一个类变量

var selectedRow = -1

所以在您的cellForRowAtIndexPath 中,您需要检查选定的行索引

// check if selected
if indexPath.row == selectedRow {
    cell.layer.borderWidth = 7
    cell.layer.borderColor = UIColor.blueColor().CGColor
}
else {
    cell.layer.borderWidth = 0
}

在您的didSelectRowAtIndexPath 需要重新加载单元格

tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: true)

【讨论】:

    【解决方案2】:

    这是我在阅读第 2 个 cmets 后发现的简单解决方案

        let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
        cell!.layer.borderWidth = 7
        cell!.layer.borderColor = UIColor.blueColor().CGColor
    

    【讨论】:

      【解决方案3】:

      cellfotitemAtIndexPath

      if(cell.isselected)
      {
      cell.layer.borderWidth = 7
          cell.layer.borderColor = UIColor.blueColor().CGColor
      }
      else
      {
      //No border and no border color
      }
      

      DidSelectitemAtIndexPath

      重新加载你的收藏视图

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-04
        • 2018-11-19
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        • 2019-03-03
        • 1970-01-01
        相关资源
        最近更新 更多