UICollectionViewCell虚线边框

时间:2016-11-22 14:21:32

标签: ios objective-c border uicollectionviewcell cashapelayer

我想让我的自定义UICollectionViewCell在它周围有一个虚线边框,我已经尝试过使用layer和bezier路径但是没有一种方法有帮助。

2 个答案:

答案 0 :(得分:0)

在你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);

}

答案 1 :(得分:0)

在班上添加此方法。

- (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;
相关问题