如何使用界面生成器向视图添加阴影?
How do I add shadows to a view using interface builder?
我读到 @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(并在 Interface builder 中将其设置为 1)
@IBInspectable var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
并从 cornerRadius
中删除 layer.masksToBounds = (newValue > 0)
。
你还缺少:
yourView.layer.shadowOpacity = 1
试试这个
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()
中调用此函数
我读到 @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(并在 Interface builder 中将其设置为 1)
@IBInspectable var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
并从 cornerRadius
中删除 layer.masksToBounds = (newValue > 0)
。
你还缺少:
yourView.layer.shadowOpacity = 1
试试这个
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()