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

后端 未结 14 1056
心在旅途
心在旅途 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:20

    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.

    0 讨论(0)
  • 2020-11-30 17:24

    Try this code:

    view.layer.borderColor =  [UIColor redColor].CGColor;
    view.layer.borderWidth= 2.0;
    [view setClipsToBounds:YES];
    
    0 讨论(0)
  • 2020-11-30 17:24

    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
    
    0 讨论(0)
  • 2020-11-30 17:26

    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 ;-)

    0 讨论(0)
  • 2020-11-30 17:28

    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.

    0 讨论(0)
  • 2020-11-30 17:30

    @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
        }
    }
    
    0 讨论(0)
提交回复
热议问题