【发布时间】:2016-11-22 14:21:31
【问题描述】:
我想让我的自定义 UICollectionViewCell 周围有一个虚线边框,我尝试使用图层和贝塞尔路径,但没有任何方法有帮助。
【问题讨论】:
标签: ios objective-c border uicollectionviewcell cashapelayer
我想让我的自定义 UICollectionViewCell 周围有一个虚线边框,我尝试使用图层和贝塞尔路径,但没有任何方法有帮助。
【问题讨论】:
标签: ios objective-c border uicollectionviewcell cashapelayer
在你UICollectionViewCell's子类
static CGFloat const kDashedBorderWidth = (2.0f);
static CGFloat const kDashedPhase = (0.0f);
static CGFloat const kDashedLinesLength[] = {4.0f, 2.0f};
static size_t const kDashedCount = (2.0f);
-(void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, kDashedBorderWidth);
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetLineDash(context, kDashedPhase, kDashedLinesLength, kDashedCount) ;
CGContextAddRect(context, rect);
CGContextStrokePath(context);
}
【讨论】:
在你的类中添加这个方法。
- (CAShapeLayer *) addDashedBorderWithColor: (CGColorRef)color withSize:(CGSize)size{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGSize frameSize = size;
CGRect shapeRect = CGRectMake(0.0f, 0.0f, frameSize.width, frameSize.height);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake( frameSize.width/2,frameSize.height/2)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:color];
[shapeLayer setLineWidth:5.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:10],
[NSNumber numberWithInt:5],
nil]];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:15.0];
[shapeLayer setPath:path.CGPath];
return shapeLayer;
}
在您的cellForRowAtIndexPath 方法中写入以下代码。
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier"@"cell"];
//Do what you want to set in your collectionViewCell
CAShapeLayer *maskLayer= [self addDashedBorderWithColor:[UIColor whiteColor].CGColor withSize:cell.borderView.frame.size];
cell.layer.mask = maskLayer;
【讨论】: