在IOS开发中,我们经常会用的贝塞尔曲线,各种处理图形,如果配合tableview用。那么这段代码放在什么位置呢?这是我做的项目中遇到的问题。可以看到,前两个cell并没有生成这个贝塞尔曲线处理view。而且是在复用之后才将他显示出来。效果如下:
cellforRow中源代码如下:
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.leftView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = cell.leftView.bounds;
maskLayer.path = maskPath.CGPath;
cell.leftView.layer.mask = maskLayer;
我们来分析问题原因,通过断点,我们可以看到调用顺序。取cell,自定义cell类的init方法,贝塞尔设置的调用,最后调用drawrect。记住关键在于。要显示之前,才会调用drawrect。这样之前设置的贝塞尔就没用了。两种方法解决这个问题。
1.在设置贝塞尔之前。强制绘图。代码如下:
[cell setNeedsDisplay];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.leftView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = cell.leftView.bounds;
maskLayer.path = maskPath.CGPath;
2.在自定义cell的类中重写drawrect方法。drawrect让贝塞尔的相关设置都在drawrect方法中走。
@implementation realTimeCell
- (void)drawRect:(CGRect)rect {
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.leftView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.leftView.bounds;
maskLayer.path = maskPath.CGPath;
self.leftView.layer.mask = maskLayer;
}
第一种方法经常不好使,可能涉及到一些时序问题。所以推荐第二种方法。100%合理,100%成功。