2016.4.6 更新 增加边框功能,调用的时候设置边框线宽度与颜色即可,具体见 效果预览:
2016.2.4 更新 重新修改了代码,一句话即可使用,具体见
自己写的一个实现TableView
的每个分组四角是圆角。 效果如下:
我是通过自定义TableViewCell
来实现这个功能的,外部引用的时候,通过判断该cell
在section
中所处的位置来判断其圆角类型。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *kCellID = @"CELLID"; KKRoundCornerCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID]; if (!cell) { cell = [[KKRoundCornerCell alloc] initWithCornerRadius:10.0f Style:UITableViewCellStyleDefault reuseIdentifier:kCellID]; } if ([tableView numberOfRowsInSection:indexPath.section] == 1) { cell.roundCornerType = KKRoundCornerCellTypeSingleRow; } else if (indexPath.row == 0) { cell.roundCornerType = KKRoundCornerCellTypeTop; } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1) { cell.roundCornerType = KKRoundCornerCellTypeBottom; } else { cell.roundCornerType = KKRoundCornerCellTypeDefault; } cell.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1.0]; cell.textLabel.text = [NSString stringWithFormat:@"第%ld组第%ld行", indexPath.section + 1, indexPath.row + 1]; return cell;}复制代码
圆角是使用贝赛尔曲线画出来然后使用layer.mask
实现。
- (void)setFrame:(CGRect)frame { [super setFrame:frame]; UIBezierPath *path; switch (_roundCornerType) { case KKRoundCornerCellTypeTop: { path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(_cornerRadius, _cornerRadius)]; break; } case KKRoundCornerCellTypeBottom: { path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(_cornerRadius, _cornerRadius)]; break; } case KKRoundCornerCellTypeSingleRow: { path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(_cornerRadius, _cornerRadius)]; break; } case KKRoundCornerCellTypeDefault: default: { self.layer.mask = nil; return; } } CAShapeLayer *maskLayer = [CAShapeLayer layer]; maskLayer.frame = self.bounds; maskLayer.path = path.CGPath; self.layer.mask = maskLayer; }复制代码
代码其实很简单,操作过程中发现系统刚创建出来的TableViewCell
的宽度默认是320,要把mask
写在setFrame:
里面。
代码已上传至