我有一个名为 RoundedView
的 UIView
自定义子类:
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
}
}
}
通过这个类,我希望能够使用 Xcode Interface Builder 设置 View 的阴影。
不幸的是,这种行为很奇怪。当设置颜色为蓝色、偏移量为CGSize.zero
、半径为0、不透明度为1时,整个阴影向右移动:
这是 1. 阴影路径、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
并在其中添加行来解决。
关于ios - 为什么我的阴影层位置不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50046010/