簡體   English   中英

檢測UIView在動畫期間何時更改大小以移動陰影

[英]Detect when UIView changes size during animation for shadow to move

UIView子類中,我具有以下用於override var bounds: CGRect屬性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 ,則UIView.animate

問題是這樣的:

移動視圖gif

我希望陰影在視圖移動時跟隨。 在gif的末尾,陰影位置和視圖位置是正確的,因為覆蓋將忽略動畫,並假裝它已經進行了動畫處理。

我怎樣才能解決這個問題?

嘗試更新的shadowlayoutSubviews()CustomView ,即

class CustomView: UIView {
    override func layoutSubviews() {
        super.layoutSubviews()

        self.layer.shadowRadius = 10.0
        self.layer.shadowOpacity = 1.0
        self.layer.shadowColor = UIColor.black.cgColor

        let oldPath = self.layer.shadowPath
        let newPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 0.0).cgPath
        if oldPath != nil {
            let shadowPathAnimation: CABasicAnimation = CABasicAnimation(keyPath: "shadowPath")
            shadowPathAnimation.fromValue = oldPath
            shadowPathAnimation.toValue = newPath
            self.layer.add(shadowPathAnimation, forKey: "shadowAnimation")
            self.layer.shadowPath = newPath
        }
    }
}

class ViewController: UIViewController {
    @IBOutlet weak var customView: CustomView!
    @IBOutlet weak var trailingConstraint: NSLayoutConstraint!

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        UIView.animate(withDuration: 3.0) {
            self.trailingConstraint.constant = 200.0
            self.view.layoutIfNeeded()
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM