gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:38:35 24 4
gpt4 key购买 nike

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
}
}
}

当 View 约束被动画化(导致 View 改变大小)时,随着边界的变化,尝试多次重新绘制阴影。

但是,边界会立即发生变化,因为动画只是视觉效果。有没有办法让这个阴影在动画时跟随 View ?如果这可以放在 UIView 子类中而不是动画 block 中,那就更好了,它是 UIView.animate

问题如下:

Moving view gif

我希望阴影在 View 移动时跟随。在 gif 的末尾,阴影位置和 View 位置是正确的,因为覆盖忽略了动画并假装它已经设置了动画。

我该如何解决这个问题?

最佳答案

尝试更新 CustomViewlayoutSubviews() 中的 shadow,即

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()
}
}
}

关于ios - 检测 UIView 在动画期间何时更改大小以使阴影移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com