为什么我的阴影层没有正确定位?

时间:2018-04-26 14:47:40

标签: ios swift scrollview shadow

我有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 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)

我不知道为什么会这样。你能救我一下吗?

1 个答案:

答案 0 :(得分:0)

我不能简单地把这一行

layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath

进入每个didSet观察者,因为帧可能仍然会改变。

通过覆盖函数layoutSubviews并在那里添加行来解决。

相关问题