我得到了一个名为UIView
的自定义子类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
}
}
}
使用这个类,我希望能够使用Xcode接口生成器为视图设置阴影。不幸的是,这种行为非常奇怪;当将颜色设置为蓝色,偏移量设置为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)
我不知道为什么会这样。我可以请您帮个忙吗?
发布于 2018-04-26 11:15:58
我不能简单地说这句话
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
加入到每个didSet观察者中,因为框架可能仍然会改变。
通过重写函数layoutSubviews
并在其中添加行来解决问题。
https://stackoverflow.com/questions/50046010
复制