iOS 13 新增分组圆角,属性UITableViewStyleInsetGrouped
- (UITableView *)tableView{
if (!_tableView) {
if (@available(iOS 13.0, *)) {
_tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleInsetGrouped];
} else {
// Fallback on earlier versions
}
为了兼容iOS13之前机型,可以使用贝塞尔曲线实现section圆角
- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
// 圆角角度
CGFloat radius = 10.f;
// 设置cell 背景色为透明
cell.backgroundColor = UIColor.clearColor;
// 创建两个layer
CAShapeLayer *normalLayer = [[CAShapeLayer alloc] init];
CAShapeLayer *selectLayer = [[CAShapeLayer alloc] init];
// 获取显示区域大小
CGRect bounds = CGRectInset(cell.bounds, 15, 0);
// 获取每组行数
NSInteger rowNum = [tableView numberOfRowsInSection:indexPath.section];
// 贝塞尔曲线
UIBezierPath *bezierPath = nil;
if (rowNum == 1) {
bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
}else{
if (indexPath.row == 0) {
// 每组第一行(添加左上和右上的圆角)
bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(radius, radius)];
}else if (indexPath.row == rowNum - 1){
// 每组最后一行(添加左下和右下的圆角)
bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(radius, radius)];
}else{
// 每组不是首位的行不设置圆角
bezierPath = [UIBezierPath bezierPathWithRect:bounds];
}
}
// 把已经绘制好的贝塞尔曲线路径赋值给图层,然后图层根据path进行图像渲染render
normalLayer.path = bezierPath.CGPath;
selectLayer.path = bezierPath.CGPath;
UIView *nomarBgView = [[UIView alloc] initWithFrame:bounds];
// 设置填充颜色
// normalLayer.fillColor = [UIColor colorWithWhite:0.95 alpha:1.0].CGColor;
normalLayer.fillColor = [[UIColor whiteColor] CGColor];
// 添加图层到nomarBgView中
[nomarBgView.layer insertSublayer:normalLayer atIndex:0];
nomarBgView.backgroundColor = UIColor.clearColor;
// nomarBgView.backgroundColor = UIColor.whiteColor;
cell.backgroundView = nomarBgView;
//此时圆角显示就完成了,但是如果没有取消cell的点击效果,还是会出现一个灰色的长方形的形状,再用上面创建的selectLayer给cell添加一个selectedBackgroundView
UIView *selectBgView = [[UIView alloc] initWithFrame:bounds];
selectLayer.fillColor = [[UIColor whiteColor] CGColor];
[selectBgView.layer insertSublayer:selectLayer atIndex:0];
selectBgView.backgroundColor = UIColor.clearColor;
cell.selectedBackgroundView = selectBgView;
}
效果如下:
网友评论