我的按钮正在使用自动布局调整大小。该按钮有一个CAShapeLayer,它的框架设置在layoutSubviews
:
var initial = true
override func layoutSubviews() {
super.layoutSubviews()
if initial {
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
initial = false
}
}
因此,只要更改此按钮的大小,就会立即更改图层而不进行任何动画(隐藏按钮动画本身)。
我试图添加动画:
override func layoutSubviews() {
super.layoutSubviews()
func movePosition() {
let fromValue = border.position.x
let toValue = center.x
CATransaction.setDisableActions(true)
border.position.x = toValue
let positionAnimation = CABasicAnimation(keyPath: "position.x")
positionAnimation.fromValue = fromValue
positionAnimation.toValue = toValue
positionAnimation.duration = 0.5
border.addAnimation(positionAnimation, forKey: "position")
}
func changesWidth() {
let fromValue = border.frame.size.width
let toValue = layer.bounds.width
CATransaction.setDisableActions(true)
border.frame.size.width = toValue
let widthAnimation = CABasicAnimation(keyPath: "frame.size.width")
widthAnimation.fromValue = fromValue
widthAnimation.toValue = toValue
widthAnimation.duration = 0.5
border.addAnimation(widthAnimation, forKey: "width")
}
if initial {
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
initial = false
} else {
movePosition()
changesWidth()
}
}
但是有了这个,动画完全搞砸了(最初调用了layoutSubview
几次,所以它在开始时会混淆各层。
尝试在layoutSubviews
中动画图层是否正确?或者我应该手动计算宽度并从那里为图层设置动画?