我建议使用UITableViewCell子类,并将自定义视图的自定义视图添加到contentView中。
这是我的简单实现。
#import "TableViewCell.h"
#import "RoundedView.h"
@implementation TableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
RoundedView *roundedView = [[RoundedView alloc] initWithFrame:CGRectInset(self.contentView.bounds, 2, 2)];
[self.contentView addSubview:roundedView];
}
return self;
}
@end
而圆形我简单地设置圆角到所需的边缘。
#import "RoundedView.h"
@implementation RoundedView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
UIBezierPath *bp = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomLeft cornerRadii:CGSizeMake(10, 10)];
CGContextAddPath(context, bp.CGPath);
CGContextClip(context);
[[UIColor brownColor] setFill];
UIRectFill(rect);
}
@end
而且里面的cellForRowAtIndexPath :,
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
if(!cell){
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
}
return cell;
}
注意,因为该视图被添加到细胞里面只有initWithStyle:reuseIdentifier:方法,认为只会当一个新的小区分配借鉴。大多数情况下,UITableView会使单元出队,所以这只是很少的时间。
而最终的结果是这样的,
你能解释一下为什么这会在性能上是最好的? –
如果单元格不存在,则对其执行自定义修改 - 对于每个**被检测的新单元格,这只会发生一次** - 而不是在if语句之外执行,这将导致自定义更改将被执行多次,也就是每个正在显示的单元格。 – royherma
那么既然你在重复使用单元格,它只会在第一次创建时调用这些更改? –