Cocoa Touch: How To Change UIView's Border Color And Thickness?

后端 未结 14 1055
心在旅途
心在旅途 2020-11-30 16:56

I saw in the inspector that I can change the background color, but I\'d like to also change the border color and thickness, is this possible?

相关标签:
14条回答
  • 2020-11-30 17:35

    I wanted to add this to @marczking's answer (Option 1) as a comment, but my lowly status on StackOverflow is preventing that.

    I did a port of @marczking's answer to Objective C. Works like charm, thanks @marczking!

    UIView+Border.h:

    #import <UIKit/UIKit.h>
    
    IB_DESIGNABLE
    @interface UIView (Border)
    
    -(void)setBorderColor:(UIColor *)color;
    -(void)setBorderWidth:(CGFloat)width;
    -(void)setCornerRadius:(CGFloat)radius;
    
    @end
    

    UIView+Border.m:

    #import "UIView+Border.h"
    
    @implementation UIView (Border)
    // Note: cannot use synthesize in a Category
    
    -(void)setBorderColor:(UIColor *)color
    {
        self.layer.borderColor = color.CGColor;
    }
    
    -(void)setBorderWidth:(CGFloat)width
    {
        self.layer.borderWidth = width;
    }
    
    -(void)setCornerRadius:(CGFloat)radius
    {
        self.layer.cornerRadius = radius;
        self.layer.masksToBounds = radius > 0;
    }
    
    @end
    
    0 讨论(0)
  • 2020-11-30 17:40

    You can also create border with the color of your wish..

    view.layer.borderColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0].CGColor;
    

    *r,g,b are the values between 0 to 255.

    0 讨论(0)
提交回复
热议问题