UIView Shadow using User Defined Runtime Attributes

淺唱寂寞╮ 提交于 2019-12-05 10:10:30

It is indeed as you stated because the Color type in the User Defined Runtime Attributes panel creates a UIColor, but layer.borderColor holds a cgColor type.

You could solve this by creating a category that allows a proxy color to be set through Interface Builder:

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

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

But a much nicer way is to use IBDesignable instead of User Defined Runtime Attributes, it is more clear.

You do this by adding a new swift file named UIViewExtentions.swift in your project (or just paste this in any file) :

import UIKit

@IBDesignable extension UIView {
    @IBInspectable var borderColor:UIColor? {
        set {
            layer.borderColor = newValue!.cgColor
        }
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor:color)
            }
            else {
                return nil
            }
        }
    }
    @IBInspectable var borderWidth:CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    @IBInspectable var cornerRadius:CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

Then this will be available in Interface Builder for every button, imageView, label, etc. in the Utilities Panel > Attributes Inspector:

Now if you set you values in the Attributes Inspector and look back at the User Defined Runtime Attributes, you'll see they are automatically filed out for you!

EDIT: For more, see: http://nshipster.com/ibinspectable-ibdesignable/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!