美文网首页
iOS 设置View的单个边的Border

iOS 设置View的单个边的Border

作者: 邓布利多教授 | 来源:发表于2019-11-01 10:59 被阅读0次

    .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 设置View的单个边的Border

          本文链接:https://www.haomeiwen.com/subject/lglfbctx.html