美文网首页
iOS 视图添加指定边框

iOS 视图添加指定边框

作者: 863cda997e42 | 来源:发表于2020-05-08 14:19 被阅读0次

    可以为视图的每个边框指定不同的颜色和宽度。可以用来添加界面中的分割线。
    头文件

    
    #import <UIKit/UIKit.h>
    
    @interface UIView (Border)
    
    -(void)addBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    -(void)addBottomBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    -(void)addLeftBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    -(void)addRightBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    -(void)addTopBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    
    @end
    

    实现文件

    
    #import "UIView+Border.h"
    
    @implementation UIView (Border)
    
    -(void)addBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth{
        self.layer.borderColor = color.CGColor;
        self.layer.borderWidth = borderWidth;
    }
    
    -(void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;
        border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
        [self.layer addSublayer:border];
    }
    
    -(void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;
        border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
        [self.layer addSublayer:border];
    }
    
    -(void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;
        border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
        [self.layer addSublayer:border];
    }
    
    -(void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;
        border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
        [self.layer addSublayer:border];
    }
    
    @end
    
    

    可以给指定的边添加边框。引入头文件 "UIView+Border.h",调用指定的方法即可。

    相关文章

      网友评论

          本文标题:iOS 视图添加指定边框

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