美文网首页iOS开发小技巧iOS 开发技巧iOS Developer
简单实现UITableVIew每组(section)圆角

简单实现UITableVIew每组(section)圆角

作者: 我在敲BUG | 来源:发表于2017-08-01 19:57 被阅读261次

效果如图

IMG_1239.PNG

实现UITableView的此代理即可:

    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
        //圆率
        CGFloat cornerRadius = 10.0;
        //大小
        CGRect bounds = cell.bounds;
        //行数
        NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
        
        //绘制曲线
        UIBezierPath *bezierPath = nil;
        
        if (indexPath.row == 0 && numberOfRows == 1) {
            //一个为一组时,四个角都为圆角
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
        } else if (indexPath.row == 0) {
            //为组的第一行时,左上、右上角为圆角
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
        } else if (indexPath.row == numberOfRows - 1) {
            //为组的最后一行,左下、右下角为圆角
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight) cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
        } else {
            //中间的都为矩形
            bezierPath = [UIBezierPath bezierPathWithRect:bounds];
        }
        //cell的背景色透明
        cell.backgroundColor = [UIColor clearColor];
        //新建一个图层
        CAShapeLayer *layer = [CAShapeLayer layer];
        //图层边框路径
        layer.path = bezierPath.CGPath;
        //图层填充色,也就是cell的底色
        layer.fillColor = [UIColor whiteColor].CGColor;
         //图层边框线条颜色
         /*
         如果self.tableView.style = UITableViewStyleGrouped时,每一组的首尾都会有一根分割线,目前我还没找到去掉每组首尾分割线,保留cell分割线的办法。
         所以这里取巧,用带颜色的图层边框替代分割线。
         这里为了美观,最好设为和tableView的底色一致。
         设为透明,好像不起作用。
         */
        layer.strokeColor = [UIColor grayColor].CGColor;
         //将图层添加到cell的图层中,并插到最底层
        [cell.layer insertSublayer:layer atIndex:0];
    }

待完善的地方:

  1. 上面提到的,不能很好的去掉组头和组尾的分割线
  2. 暂未添加阴影效果(本来是准备画路径不封闭的layer,也就是刚好画每组边框那一圈,然后添加阴影,但是还没实践)

相关文章

网友评论

  • 48d063e3b39b:让ui给个图就好啦……
  • YourSummer:你这个cell的宽度是怎样搞得, 看到距离屏幕边缘有距离
  • z小志: 对一个view 同时添加阴影与圆角 最高效 最便捷的实现方法是什么呢??
    z小志:@明月水上 那圆角部分的阴影会不会看起来很别扭
    我在敲BUG:@z小志 在view的下面再放一个同样大小的view用来作阴影,原view就用来圆角

本文标题:简单实现UITableVIew每组(section)圆角

本文链接:https://www.haomeiwen.com/subject/sklslxtx.html