2016-02-27 137 views
0

我想在用户触摸单元格时更改边框颜色。我有下面的代码在我的UICollectionView,但它不工作:更改UICollectionView中的单元格边框颜色?

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

     self.user["avatar"] = self.avatars[indexPath.row] 

     do { 
      try self.user.save() 
     } catch { 
      print(error) 
     } 

     //self.performSegueWithIdentifier("returnToProfile", sender: user) 
     let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! AvatarViewCell 
     cell.layer.borderWidth = 5.0 
     cell.layer.borderColor = UIColor.yellowColor().CGColor 

    } 

谢谢!

编辑:我试了在被标记为重复,但它仍然无法正常工作的问题中排名最高的答案。 cell.layer.borderColor = UIColor.yellowColor().CGColor不会改变颜色。

也许这是我如何定义单元格的问题?

+0

我试图在问题的答案,但它仍然没有奏效。我认为这可能是一个问题,我如何定义单元格 – winston

+1

是否尝试更改内容视图的边框? 'cell.contentView.layer.borderWidth = 1.0 cell.contentView.layer.borderColor = UIColor.yellowColor()。CGColor' – Lucho

回答

1

我使用的数据源更改单元格背景触摸时:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

     let cell = collectionView.cellForItemAtIndexPath(indexPath) as! DateCell 

     if !days.contains(Functions.tools.nextThreeWeeks().long[indexPath.row]) { 
      days.append(cell.fullDate) 
      cell.backgroundColor = UIColor(red:0.96, green:0.72, blue:0.35, alpha:1) 
     } else { 
      days = days.arrayRemovingObject(cell.fullDate) 
      cell.backgroundColor = UIColor.whiteColor() 
     } 

     print(days) 

    } 
+0

工作正常!我需要改变我的单元格定义使用'cellForItemAtIndexPath'。 – winston