在UICollectionView中更改单元格边框颜色?

时间:2016-02-27 15:10:09

标签: ios swift uicollectionview swift2

我想在用户触摸单元格时更改边框颜色。我的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不会改变颜色。

也许这是我如何定义细胞的问题?

1 个答案:

答案 0 :(得分:2)

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

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)

    }