为什么我的阴影层没有正确定位?
Why is my shadow layer not positioned correctly?
我得到了 UIView
的自定义子 class,名为 RoundedView
:
import UIKit
@IBDesignable
class RoundedView: UIView {
@IBInspectable var shadowColor : UIColor? {
didSet {
layer.shadowColor = shadowColor?.cgColor
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
@IBInspectable var shadowOffset : CGSize = CGSize(width: 20, height: 20) {
didSet {
layer.shadowOffset = shadowOffset
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
@IBInspectable var shadowRadius : CGFloat = 0.0 {
didSet {
layer.shadowRadius = shadowRadius
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
@IBInspectable var shadowOpacity : Float = 1.0 {
didSet {
layer.shadowOpacity = shadowOpacity
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
}
有了这个 class,我希望能够使用 Xcode Interface Builder 为视图设置阴影。
不幸的是,这种行为很奇怪;当设置颜色为蓝色,偏移量为 CGSize.zero
,半径为 0,不透明度为 1 时,整个阴影向右移动:
这是 1. shadowPath、2. 边界和 3. 框架的输出:
shadowPath:
Path 0x60800022e040:
moveto (0, 0)
lineto (300, 0)
lineto (300, 150)
lineto (0, 150)
closepath
self.bounds:
(0.0, 0.0, 300.0, 150.0)
self.frame:
(37.0, 268.5, 300.0, 150.0)
我不知道为什么会这样。你能帮帮我吗?
我不能简单地把这行写
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
进入每个 didSet 观察者,因为框架可能仍然会改变。
通过覆盖函数 layoutSubviews
并在其中添加行来解决。
我得到了 UIView
的自定义子 class,名为 RoundedView
:
import UIKit
@IBDesignable
class RoundedView: UIView {
@IBInspectable var shadowColor : UIColor? {
didSet {
layer.shadowColor = shadowColor?.cgColor
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
@IBInspectable var shadowOffset : CGSize = CGSize(width: 20, height: 20) {
didSet {
layer.shadowOffset = shadowOffset
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
@IBInspectable var shadowRadius : CGFloat = 0.0 {
didSet {
layer.shadowRadius = shadowRadius
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
@IBInspectable var shadowOpacity : Float = 1.0 {
didSet {
layer.shadowOpacity = shadowOpacity
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
}
有了这个 class,我希望能够使用 Xcode Interface Builder 为视图设置阴影。
不幸的是,这种行为很奇怪;当设置颜色为蓝色,偏移量为 CGSize.zero
,半径为 0,不透明度为 1 时,整个阴影向右移动:
这是 1. shadowPath、2. 边界和 3. 框架的输出:
shadowPath:
Path 0x60800022e040:
moveto (0, 0)
lineto (300, 0)
lineto (300, 150)
lineto (0, 150)
closepath
self.bounds:
(0.0, 0.0, 300.0, 150.0)
self.frame:
(37.0, 268.5, 300.0, 150.0)
我不知道为什么会这样。你能帮帮我吗?
我不能简单地把这行写
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
进入每个 didSet 观察者,因为框架可能仍然会改变。
通过覆盖函数 layoutSubviews
并在其中添加行来解决。