ChatGPT解决这个技术问题 Extra ChatGPT

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

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?


V
Vladimir

You need to use view's layer to set border property. e.g:

#import <QuartzCore/QuartzCore.h>
...
view.layer.borderColor = [UIColor redColor].CGColor;
view.layer.borderWidth = 3.0f;

You also need to link with QuartzCore.framework to access this functionality.


Is there any way to set different width/colors for every side?
@lluismontero I afraid you'll have to make custom UIView with drawRect: method for that
If I do this, and on top of this view I have an animation, like a modal UINavigationController dismissing, I see a lot of glitches happening, it's hard to describe. If I deactivate the borders, everything goes back to normal.
Just a heads up for others. Xcode suggests bridging UIColor to CGColorRef as __bridge CGColorRef. This does not work. It needs to be [UIColor blackColor].CGColor as mentioned in answer.
#import <QuartzCore/QuartzCore.h> is no longer needed.
M
MMachinegun

Xcode 6 update

Since Xcode's newest version there is a better solution to this:

With @IBInspectable you can set Attributes directly from within the Attributes Inspector.

https://i.stack.imgur.com/Vuoku.gif

This sets the User Defined Runtime Attributes for you:

https://i.stack.imgur.com/2nXiO.gif

There are two approaches to set this up:

Option 1 (with live updating in Storyboard)

Create MyCustomView. This inherits from UIView. Set @IBDesignable (this makes the View update live).* Set your Runtime Attributes (border, etc.) with @IBInspectable Change your Views Class to MyCustomView Edit in Attributes Panel and see changes in Storyboard :)

`

@IBDesignable
class MyCustomView: UIView {
    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }
    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }
    @IBInspectable var borderColor: UIColor? {
        didSet {
            layer.borderColor = borderColor?.CGColor
        }
    }
}

* @IBDesignable only works when set at the start of class MyCustomView

Option 2 (not working since Swift 1.2, see comments)

Extend your UIView Class:

extension UIView {
    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }
    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }
    @IBInspectable var borderColor: UIColor? {
        didSet {
            layer.borderColor = borderColor?.CGColor
        }
    }
}

This way, your default View always has those extra editable fields in Attributes Inspector. Another advantage is that you don't have to change the class to MycustomView every time. However, one drawback to this is that you will only see your changes when you run your app.


Your extension does not work in latest version of Xcode as of today.
I'll confirm @EdgarAroutiounian only to say that in Swift 1.2 the second approach no longer works
What about Objective-C?
Check out spencery2's answer further below, he took the time to write it in Objective-C:
update the extension to not store a value and use set(value) { } and get { } to access the layer directly, it works then.
r
rohan-patel

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.


It's worth noting that r, g and b should probably be floats; the divisors should also be floats: r / 255.0.
no, C syntax is not as You say. r, g and b can be int, as C (and objC IS C) promotions will cast int r=128 to double when making: r/255.0. By the way You got double, and Clang will cast to CGFloat.
B
Bikramjit Singh

Add following @IBInspectables in UIView extension

extension UIView {

  @IBInspectable var borderWidth: CGFloat {
    get {
      return layer.borderWidth
    }
    set(newValue) {
      layer.borderWidth = newValue
    }
  }

  @IBInspectable var borderColor: UIColor? {
    get {
      if let color = layer.borderColor {
        return UIColor(CGColor: color)
      }
      return nil
    }
    set(newValue) {
      layer.borderColor = newValue?.CGColor
    }
  }
}

And then you should be able to set borderColor and borderWidth attributes directly from Attribute inspector. See attached image

Attributes Inspector


N
Nicu Surdu

When I use Vladimir's CALayer solution, and on top of the view I have an animation, like a modal UINavigationController dismissing, I see a lot of glitches happening and having drawing performance issues.

So, another way to achieve this, but without the glitches and performance loss, is to make a custom UIView and implement the drawRect message like so:

- (void)drawRect:(CGRect)rect
{
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(contextRef, 1);
    CGContextSetRGBStrokeColor(contextRef, 255.0, 255.0, 255.0, 1.0);
    CGContextStrokeRect(contextRef, rect);    
}

@Krish You store the color in a variable and when you need to change the border color, you change the variable value and call setNeedsDisplay on the view. This will force the redraw of the UIView and implicitly will re-call drawRect. Not tested, tho ...
R
Roopendra
view.layer.borderWidth = 1.0
view.layer.borderColor = UIColor.lightGray.cgColor

I really don't like people being down voted without an explanation. It helps no-one.
V
Vikram Biwal

Try this code:

view.layer.borderColor =  [UIColor redColor].CGColor;
view.layer.borderWidth= 2.0;
[view setClipsToBounds:YES];

D
DEzra

I wouldn't suggest overriding the drawRect due to causing a performance hit.

Instead, I would modify the properties of the class like below (in your custom uiview):

  - (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
      self.layer.borderWidth = 2.f;
      self.layer.borderColor = [UIColor redColor].CGColor;
    }
  return self;

I didn't see any glitches when taking above approach - not sure why putting in the initWithFrame stops these ;-)


s
spencery2

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

a
anhtran

@IBInspectable is working for me on iOS 9 , Swift 2.0

extension UIView {

@IBInspectable var borderWidth: CGFloat {
get {
        return layer.borderWidth
    }
    set(newValue) {
        layer.borderWidth = newValue
    }
}

@IBInspectable var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set(newValue) {
        layer.cornerRadius = newValue
    }
}

@IBInspectable var borderColor: UIColor? {
    get {
        if let color = layer.borderColor {
            return UIColor(CGColor: color)
        }
        return nil
    }
    set(newValue) {
        layer.borderColor = newValue?.CGColor
    }
}

M
Matt Becker

If you didn't want to edit the layer of a UIView, you could always embed the view within another view. The parent view would have its background color set to the border color. It would also be slightly larger, depending upon how wide you want the border to be.

Of course, this only works if your view isn't transparent and you only want a single border color. The OP wanted the border in the view itself, but this may be a viable alternative.


A
Akhrua

item's border color in swift 4.2:

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell_lastOrderId") as! Cell_lastOrder
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.white.cgColor
cell.layer.cornerRadius = 10

Y
Yuanfei Zhu

If you want to add different border on different sides, may be add a subview with the specific style is a way easy to come up with.


N
Nitin singh

[self.view.layer setBorderColor: [UIColor colorWithRed:0.265 green:0.447 blue:0.767 alpha:1.0f].CGColor];