iOS 设置View的单个边的Border

释放双眼,带上耳机,听听看~!
.h文件

 

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIView (LYUnilateralBorder)

@property (nonatomic) CGFloat height;
@property (nonatomic) CGFloat width;

-(void)setBorderWithTop:(BOOL)top
                   Left:(BOOL)left
                 Bottom:(BOOL)bottom
                  Right:(BOOL)right
            BorderColor:(UIColor *)borderColor
            BorderWidth:(CGFloat)borderWidth;

@end

NS_ASSUME_NONNULL_END

.m文件

 

#import "UIView+LYUnilateralBorder.h"

@implementation UIView (LYUnilateralBorder)

- (void)setHeight:(CGFloat)height{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (CGFloat)height{
    return self.frame.size.height;
}

- (void)setWidth:(CGFloat)width{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)width{
    return self.frame.size.width;
}

-(void)setBorderWithTop:(BOOL)top Left:(BOOL)left Bottom:(BOOL)bottom Right:(BOOL)right BorderColor:(UIColor *)borderColor BorderWidth:(CGFloat)borderWidth{
    
    if (top) {
        CALayer *topBorder = [CALayer layer];
        topBorder.frame = CGRectMake(0, 0, self.width, borderWidth * 1.5);
        topBorder.backgroundColor = borderColor.CGColor;
        [self.layer addSublayer:topBorder];
    }
    
    if (left) {
        CALayer *leftBorder = [CALayer layer];
        leftBorder.frame = CGRectMake(0, 0, borderWidth * 1.5, self.height);
        leftBorder.backgroundColor = borderColor.CGColor;
        [self.layer addSublayer:leftBorder];
    }
    
    if (bottom) {
        CALayer *bottomBorder = [CALayer layer];
        bottomBorder.frame = CGRectMake(0, self.height - borderWidth * 1.5, self.width, borderWidth * 1.5);
        bottomBorder.backgroundColor = borderColor.CGColor;
        [self.layer addSublayer:bottomBorder];
    }
    
    if (right) {
        CALayer *rightBorder = [CALayer layer];
        rightBorder.frame = CGRectMake(self.width - borderWidth * 1.5, 0, borderWidth * 1.5, self.height);
        rightBorder.backgroundColor = borderColor.CGColor;
        [self.layer addSublayer:rightBorder];
    }
    
}

@end

调用方式

  • 引入头文件#import "UIView+LYUnilateralBorder.h"
  • 对需要设置的View设置,例如UITextFiled

 

[_tfNumber setBorderWithTop:YES Left:NO Bottom:YES Right:NO BorderColor:LYColor_Black_3 BorderWidth:0.7];

人已赞赏
iOS文章

iOS 3D Touch

2019-12-24 9:05:49

iOS文章

iOS 3D Touch之Peek &Pop

2019-12-24 13:06:31

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索