自定义UICollectionViewFlowLayout边框

时间:2015-11-08 21:35:14

标签: ios uicollectionview swift2 ios9 uicollectionviewlayout

我创建了一个继承自UICollectionViewFlowLayout的Swift类,并且我已经能够成功地做一些巧妙的事情,比如改变它绘制的每个框之间的间距。我正在绘制日历,所以想象28-31个盒子,每行7个,具体取决于月份。

..我从未想过的一件事是如何做一些事情,比如将正确的边框留空而不是。或顶部边框。我最近在每个框之间将间距更改为0,现在框的边框重叠。

我喜欢以编程方式将所有正确的边框留空,以使其下一个边框的左边框充当相互边框(因此它不是双边框)。然后,在每行的集合中的最后一个框中,我可以使它具有右边框。知道我在说什么吗?每个盒子周围都有漂亮的薄边框。

我是否在我的覆盖功能layoutAttributesForElementsInRect(rect:CGRect)中执行此操作 - > [UICollectionViewLayoutAttributes]?也许在其他地方?

谢谢!

2 个答案:

答案 0 :(得分:2)

BANG!我想到了。这太酷了,因为现在我可以通过编程方式决定何时添加下面的边框(例如,如果x然后是day.layer.addSublayer(topBorder),否则不要添加它)

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
    {
        let day = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CalendarDayCollectionViewCell

        /* adds a border to entire grid */
        day.layer.borderColor = UIColor.lightGrayColor().CGColor
        //day.layer.borderWidth = 1  //can also do .cornerRadius to round out borders



        //top border
        let topBorder = CALayer()
        topBorder.frame = CGRectMake(0.0, 0.0, day.frame.size.width, 1.0);
        topBorder.backgroundColor = UIColor(white: 0.8, alpha: 1.0).CGColor


        // bottom border
        let bottomBorder = CALayer()
        bottomBorder.frame = CGRectMake(0.0, day.frame.size.height-1, day.frame.size.width, 1.0);
        bottomBorder.backgroundColor = UIColor(white: 0.8, alpha: 1.0).CGColor

        let leftBorder = CALayer()
        leftBorder.frame = CGRectMake(0.0, 0.0, 1.0, day.frame.size.height);
        leftBorder.backgroundColor = UIColor(white: 0.8, alpha: 1.0).CGColor

        let rightBorder = CALayer()
        rightBorder.frame = CGRectMake(day.frame.size.width - 1, 0.0, 1.0, day.frame.size.height);
        rightBorder.backgroundColor = UIColor(white: 0.8, alpha: 1.0).CGColor

        day.layer.addSublayer(topBorder)
        day.layer.addSublayer(bottomBorder)
        day.layer.addSublayer(leftBorder)
        day.layer.addSublayer(rightBorder)

return day
}

答案 1 :(得分:0)

您无法真正明确删除边框的一侧或两侧,而不是CALayer支持。

但基于此answer,你应该能够通过重叠单元格来实现,所以你应该覆盖func layoutAttributesForElementsInRect(rect: CGRect)

是正确的 顺便说一下,我想你可以试试

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    let borderWidth = 5
    return UIEdgeInsetsMake(-borderWidth,-borderWidth,-borderWidth,-borderWidth);
}
相关问题