检测UIView在动画期间何时更改大小以移动阴影

时间:2019-05-27 12:13:30

标签: ios swift uiview uiviewanimation shadow

UIView子类中,我为override var bounds: CGRect设置了以下属性:

@IBDesignable
class GEView: UIView {

    private var shadowView: UIView? {
        didSet {
            guard let superview = superview else { return }
            guard let shadowView = self.shadowView else { return }

            // Add the shadow to the superview, as the shadow cannot
            // also allow rounded corners simultaneously
            superview.addSubview(shadowView)
            shadowView.layer.zPosition = layer.zPosition - 1
            shadowView.edges(to: self)
        }
    }

    // CALLED WHEN SETTING @IBInspectable PROPERTIES
    /// Creates a shadow if one has not yet been created.
    private func createShadowIfNeeded() {
        guard shadowView == nil else { return }

        shadowView = UIView()

        shadowView?.layer.shadowPath = UIBezierPath(roundedRect:    bounds,
                                                    cornerRadius:   cornerRadius).cgPath
        shadowView?.layer.shouldRasterize = true
    }


    // THE PROPERTY TO ATTEMPT THE SHADOW MOVING
    override var bounds: CGRect {
        didSet {
            shadowView?.layer.shadowPath = UIBezierPath(roundedRect:    bounds,
                                                        cornerRadius:   cornerRadius).cgPath
        }
    }
}

当视图约束设置为动画(导致视图大小更改)时,随着边界的变化,尝试多次重绘阴影。

但是,由于动画只是视觉效果,边界会立即更改。有没有办法让这个阴影在动画时跟随该视图?最好将它放在UIView子类中,而不是UIView.animate的动画块中。

问题出在这里:

Moving view gif

我希望阴影随着视图移动而跟随。在gif的末尾,阴影位置和视图位置是正确的,因为替代会忽略动画,并假装它已经动画化。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

尝试更新shadow的{​​{1}}中的layoutSubviews(),即

CustomView