Runtime BorderColor is not working in Xcode 9

ios swift xcode

619 观看

2回复

145 作者的声誉

I made a extension of CALayer for border color as a runtime attribute, but it is not working.

It shows default black color only.

extension CALayer {
    var borderUIColor: UIColor {
        set {
            self.borderColor = newValue.cgColor
        }

        get {
            return UIColor(cgColor: self.borderColor!)
        }
    }
}

enter image description here

作者: nirav 的来源 发布者: 2017 年 9 月 15 日

回应 2


0

31 作者的声誉

Try this:

extension UILabel{
    func setBorderColor(width:CGFloat,color:UIColor) -> Void
    {
        self.layer.borderColor = color.cgColor
        self.layer.borderWidth = width
    }
}

and implement this function wherever you want,like this

label.setBorderColor(width: 2.0, color: UIColor.brown)

Hope this helps!

作者: Judit 发布者: 2017 年 9 月 15 日

1

11781 作者的声誉

You should handle nil values with care, and may create an extension to UIView which declares the property as @IBInspectabe:

import UIKit

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

This makes it much easier to set the border color in Attribute Inspector.

EDIT: Your example works for me with Xcode 9.0 and 8.3.3 as well. Probably it was a bug in a beta version.

作者: clemens 发布者: 2017 年 9 月 15 日
32x32