我认为解决这个问题的一种简单方法是像这样为约束常量设置动画:
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
UIView.animate(withDuration: 3, animations: {
self. heightConstaint.constant = 300 // This constant is the height of top big view.
self.view.layoutIfNeeded()}
CAShapeLayer 所在的另一个视图。我称之为line View。它的高度应限制为与top big view 的高度相同。
在line view,可以添加动画。这应该与您的实现类似。
override func didMoveToSuperview() {
super.didMoveToSuperview()
dashedLayer.backgroundColor = UIColor.clear.cgColor
layer.addSublayer(dashedLayer)
height = bounds.size.height
}
override func layoutSubviews() {
super.layoutSubviews()
let centerX = bounds.size.width / 2
let path = CGMutablePath()
path.addLines(between: [CGPoint(x: centerX, y: 0), CGPoint(x: centerX, y: frame.height)])
dashedLayer.path = path
dashedLayer.lineWidth = 3.0
dashedLayer.strokeColor = UIColor.blue.cgColor
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = height / bounds.size.height
animation.toValue = 1.0
animation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)
height = bounds.size.height
animation.duration = 3.0
dashedLayer.add(animation, forKey: nil)
}
这里正在扩展。您可以自己修改代码以适应合同。
以下是倒车动画。
override func didMoveToSuperview() {
super.didMoveToSuperview()
dashedLayer.backgroundColor = UIColor.clear.cgColor
layer.addSublayer(dashedLayer)
height = bounds.size.height
clipsToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
let centerX = bounds.size.width / 2
let path = CGMutablePath()
path.addLines(between: [CGPoint(x: centerX, y: 0), CGPoint(x: centerX, y: max(height , bounds.size.height) )])
dashedLayer.path = path
dashedLayer.lineWidth = 3.0
dashedLayer.strokeColor = UIColor.blue.cgColor
let animation = CABasicAnimation(keyPath: "strokeEnd")
if (height < bounds.size.height){
animation.fromValue = height / bounds.size.height
animation.toValue = 1.0}
else {
animation.fromValue = 1.0
animation.toValue = bounds.size.height / height}
animation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)
height = bounds.size.height
animation.duration = 3
dashedLayer.add(animation, forKey: nil)
}