虚线边框的UIButton

简单说明

使用CAShapeLayer创建虚线, 在layoutSubviews时调整其frame.

ASDotBorderButton.h

#import <UIKit/UIKit.h>

/**
 虚线边Button
 */
@interface ASDotBorderButton : UIButton

@property (nonatomic, readwrite, strong) CAShapeLayer *dotShapeLayer;

/**
 虚线颜色
 */
@property (nonatomic, readwrite, strong) UIColor *dotBorderColor;

/**
 点击状态的虚线颜色
 */
@property (nonatomic, readwrite, strong) UIColor *highlightedBorderColor;

/**
 虚线圆角,会同步设置layer.cornerRadius
 */
@property (nonatomic, readwrite, assign) CGFloat dotBorderCornerRadius;

/**
 虚线样式,默认为 @[@4, @2]
 */
@property (nonatomic, readwrite, copy) NSArray<NSNumber *> *lineDashPattern;

@end

ASDorBorderButton.m

#import "ASDotBorderButton.h"

@implementation ASDotBorderButton

- (void)layoutSubviews{
    [super layoutSubviews];

    if (!self.dotShapeLayer){
        self.dotShapeLayer = [[CAShapeLayer alloc] init];
        [self.layer addSublayer:self.dotShapeLayer];
    }

    self.dotShapeLayer.frame = self.bounds;

    CGFloat cornerRadius = 5.0f;
    if (self.dotBorderCornerRadius > 0
        && self.dotBorderCornerRadius < self.frame.size.height
        && self.dotBorderCornerRadius < self.frame.size.width){
        cornerRadius = self.dotBorderCornerRadius;
    }    
    self.layer.cornerRadius = cornerRadius;

    self.dotShapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:self.dotShapeLayer.bounds
                                                         cornerRadius:cornerRadius].CGPath;

    self.dotShapeLayer.lineWidth = 1.0f;
    if (self.lineDashPattern) {
        self.dotShapeLayer.lineDashPattern = self.lineDashPattern;
    } else {
        self.dotShapeLayer.lineDashPattern = @[@4, @2];
    }

    self.dotShapeLayer.fillColor = [UIColor clearColor].CGColor;

    if (self.highlighted && self.highlightedBorderColor){
        self.dotShapeLayer.strokeColor = self.highlightedBorderColor.CGColor;
    }else{
        if (self.dotBorderColor){
            self.dotShapeLayer.strokeColor = self.dotBorderColor.CGColor;
        }else{
            self.dotShapeLayer.strokeColor = [UIColor colorWithRed:0.824 green:0.824 blue:0.824 alpha:1.00].CGColor;
        }
    }
}

- (void)setDotBorderColor:(UIColor *)dotBorderColor{
    _dotBorderColor = dotBorderColor;

    [self setNeedsDisplay];
}

- (void)setHighlightedBorderColor:(UIColor *)highlightedBorderColor{
    _highlightedBorderColor = highlightedBorderColor;

    [self setNeedsDisplay];
}

- (void)setDotBorderCornerRadius:(CGFloat)dotBorderCornerRadius{
    _dotBorderCornerRadius = dotBorderCornerRadius;

    self.layer.cornerRadius = _dotBorderCornerRadius;

    [self setNeedsDisplay];
}

- (void)setLineDashPattern:(NSArray<NSNumber *> *)lineDashPattern
{
    _lineDashPattern = [lineDashPattern copy];

    [self setNeedsDisplay];
}

@end

标签:none