最近接了一个新需求,需要给collectionView的每个section都加上圆角效果(如下图),这样我想的办法是给每个section的头视图的两个上交变成圆角,同时将每个section最后一排的最左和最右两个cell加上圆角.
截屏2020-07-20 下午2.32.59.png
1.给头视图坐上和右上两个角加上圆角
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//1创建头视图
UICollectionReusableView *header = [[UICollectionReusableView alloc] init];
header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"PBSubappHeader" forIndexPath:indexPath];
for(UIView *subView in header.subviews) {
[subView removeFromSuperview];
}
UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 15, kScreenWidth - 30 - 1, 55)];
whiteView.backgroundColor = [UIColor whiteColor];
[header addSubview:whiteView];
//2.通过枚举设置需要改变的角用 | 分割,后面一个cornerRadii是圆角的大小
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:whiteView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = whiteView.bounds;
maskLayer.path = maskPath.CGPath;
whiteView.layer.mask = maskLayer;
}
2.给cell加圆角
为了达到图中的效果,我需要把每个section对象的个数补齐成3的倍数
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
UIBezierPath *maskPath;
CGRect boardRect;
float h = cell.bounds.size.height;
float w = cell.bounds.size.width;
//在这里算出来一个有多少行
PBSubappCategory *category = _otherSubapps[indexPath.section];
NSUInteger line = (category.tags.count - 1)/ 3;
if (indexPath.row == line * 3) {
//对左下的cell进行操作
boardRect = CGRectMake(0, -1, w, h);
maskPath = [[UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerBottomLeft cornerRadii:CGSizeMake(10, 10)] bezierPathByReversingPath];
} else if (indexPath.row == line * 3 + 2) {
//对右下的cell进行操作
boardRect = CGRectMake(0, -1, w, h);
maskPath = [[UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)] bezierPathByReversingPath];
}
else {
//其余的渲染不加角
boardRect = CGRectMake(0, -1, w, h);
maskPath = [UIBezierPath bezierPathWithRect:boardRect];
}
//不加这个循环在滑动的时候会改变样子,而且用for-in会崩溃
for (int i = 0; i < cell.contentView.layer.sublayers.count; i++) {
CALayer *layer = cell.contentView.layer.sublayers[i];
if ([layer.name isEqualToString:@"maskLayer"]) {
[layer removeFromSuperlayer];
}
}
//填充颜色和划线
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.name = @"maskLayer";
maskLayer.frame = boardRect;
maskLayer.path = maskPath.CGPath;
maskLayer.strokeColor = [UIColor clearColor].CGColor;
maskLayer.lineDashPattern = @[@4, @2];
maskLayer.lineWidth = 1.0f;
maskLayer.fillColor = [UIColor whiteColor].CGColor;
maskLayer.masksToBounds = YES;
[cell.contentView.layer insertSublayer:maskLayer atIndex:0];
}
这只是我能想到的一个办法,如果有其他的好方法欢迎赐教
网友评论