我已经知道@IBInspectable
和@IBDesignable
需要这样才能实现,并且我已经使其适用于cornerRadius
。唉,我的尝试对阴影参数不起作用。我的代码如下:
@IBDesignable class DesignableView: UIView {}
extension UIView {
@IBInspectable var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable var shadowColor: UIColor? {
get {
var color: UIColor? = nil
if let cgColor = layer.shadowColor {
color = UIColor(cgColor: cgColor)
}
return color
}
set {
layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable var cornerRadius: CGFloat { // This works, but not the ones above
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = (newValue > 0)
}
}
}
然后我在界面构建器中添加一个视图,并设置为DesignableView
。之后,我可以自由地更改cornerRadius
并相应地更新,但不会更新阴影参数。它们在界面构建器中可见,但操纵值并不会改变视觉效果;甚至在编译之后和在应用程序中运行时都没有。
我错过了什么?
编辑:我在这个问题的答案的帮助下检测到错误。要使其工作,请添加shadowOpacity(并在“界面”构建器中将其设置为1)@IBInspectable var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
并从layer.masksToBounds = (newValue > 0)
移除cornerRadius
。
答案 0 :(得分:1)
你错过了:
yourView.layer.shadowOpacity = 1
答案 1 :(得分:0)
试试这个
func decorateView() {
view.layer.masksToBounds = false
view.layer.shadowOffset = CGSize(width: 0, height:1)
view.layer.shadowOpacity = 0.1
view.layer.shadowRadius = 7
view.layer.shadowColor = .gray
}
在awakeFromNib()