UIView's border color in Interface builder doe

2019-01-13 09:33发布

I am trying to set up a view's layer properties via IB. Everything works except for color of the border (property layer.borderColor):

enter image description here

I remember running into this problem a year ago and I ended up doing it programatically. And still, I can do this programmatically, but I am curious why the layer.borderColorproperty never works via interface builder. I don't want to import QuartzCore, and then write extra line of code just because of this, seems like an overkill.

14条回答
Rolldiameter
2楼-- · 2019-01-13 10:09

In order to make CALayer KVC-compliant for the property borderColorFromUIColor, simply implement the

layer.borderColorFromUIColor=[UIColor red];

This link have awnser

查看更多
可以哭但决不认输i
3楼-- · 2019-01-13 10:11

In Swift, you can extend the UIButton class and add an @IBInspectable that will enable you to select a color from storyboard and set it's color (with width of 1 which can be changed). Add this at the end of your view controller:

extension UIButton{
    @IBInspectable var borderColor: UIColor? {
        get {
            return UIColor(CGColor: layer.borderColor!)
        }
        set {
            layer.borderColor = newValue?.CGColor
            layer.borderWidth = 1
        }
    }
}
查看更多
劫难
4楼-- · 2019-01-13 10:12

I think it may be because you have masksToBounds set to YES. I don't think the border is drawn within the bounds of the layer, so it won't be drawn since you're hiding everything outside of its bounds.

查看更多
仙女界的扛把子
5楼-- · 2019-01-13 10:13

I met the same issue, I worked around it by creating a custom button class:

class UIButtonWithRoundBorder: UIButton {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.layer.cornerRadius = 6
    self.layer.borderWidth = 1
    self.layer.borderColor = UIColor.whiteColor().CGColor
    self.clipsToBounds = true
}

}

Then in IB, change the type from "UIButton" to "UIButtonWithRoundBorder".

Simple and handy too. :)

查看更多
做自己的国王
6楼-- · 2019-01-13 10:13

swift4

extension CALayer {

  open override func setValue(_ value: Any?, forKey key: String) {

    /// If key is borderColor, and the value is the type of a UIColor.
     if key == "borderColor" , let color = value as? UIColor {

        /// After converting UIColor to CGColor, call the system method.
        return super.setValue(color.cgColor, forKey: key)
     }

     super.setValue(value, forKey: key)
   }
}
查看更多
该账号已被封号
7楼-- · 2019-01-13 10:15

borderColor will not work UNLESS the borderWidth property of the layer is set to a value greater than 0.

Swift 3:

button.layer.borderColor = UIColor.white.cgColor
button.layer.borderWidth = 1.0 // Default value is 0, that's why omitting this line will not make the border color show.
查看更多
登录 后发表回答