大家好我面临一个奇怪的问题。我希望在点击带动画的按钮时增加视图的宽度,这在我的情况下运行正常。我用来增加宽度的代码低于 -
@IBAction func increaseWidth(_ sender: AnyObject) {
UIView.animate(withDuration: 1.0, delay: 0, options:
[.allowUserInteraction], animations: {
print("Animation function animateStuff() started!")
let frmPlay : CGRect = self.nameLbl.frame
let originXbutton = frmPlay.origin.x
let originYbutton = frmPlay.origin.y
let originWidthbutton = frmPlay.size.width
let originHeightbutton = frmPlay.size.height
self.nameLbl.frame = CGRect(origin: CGPoint(x: originXbutton,y :originYbutton), size: CGSize(width: originWidthbutton+100, height: originHeightbutton))
}, completion: { finished in
})
}
但是我使用的代码没有减少动画的宽度。它只是减小宽度。用于减小宽度的代码低于 -
@IBAction func decreaseWidth(_ sender: AnyObject) {
UIView.animate(withDuration: 1.0, delay: 0, options:
[.allowUserInteraction], animations: {
print("Animation function animateStuff() started!")
let frmPlay : CGRect = self.nameLbl.frame
let originXbutton = frmPlay.origin.x
let originYbutton = frmPlay.origin.y
let originWidthbutton = frmPlay.size.width
let originHeightbutton = frmPlay.size.height
// self.nameLbl.frame = frmPlay
self.nameLbl.frame = CGRect(origin: CGPoint(x: originXbutton,y :originYbutton), size: CGSize(width: originWidthbutton-100, height: originHeightbutton))
}, completion: { finished in
})
}
请在我出错的地方帮忙。
答案 0 :(得分:3)
您只需使用CALayer
即可实现此动画。请尝试以下方法。
func scaleX() {
let animation = CABasicAnimation(keyPath: "transform.scale.x")
animation.fromValue = NSValue(cgSize: CGSize(width: 1, height: 1))
animation.toValue = NSValue(cgSize: CGSize(width: 1.2, height: 1))
animation.duration = 1.0
self.imageView.layer.add(animation, forKey: "Image-scale")
imageView.transform = CGAffineTransform(scaleX: 1.2, y: 1.0)
}
func reset() {
UIView.animate(withDuration: 1) {
self.imageView.transform = CGAffineTransform.identity
}
}
注意:我正在使用imageView
来测试动画。您可以指定view
来执行动画。
<强>更新强>
我建议您通过更改其帧内容大小来使用基本的UIView动画。请尝试以下方法。
override func viewDidAppear(_ animated: Bool) {
//To restrict animation repeats.
resetButton.isEnabled = false
resetButton.showsTouchWhenHighlighted = true
scaleButton.showsTouchWhenHighlighted = true
}
func scaleX() {
resetButton.isEnabled = true
scaleButton.isEnabled = false
UIView.animate(withDuration: 1) {
self.imageView.frame = CGRect(x: self.imageView.frame.origin.x, y: self.imageView.frame.origin.y, width: self.imageView.frame.width + 100, height: self.imageView.frame.height)
}
}
func reset() {
resetButton.isEnabled = false
scaleButton.isEnabled = true
UIView.animate(withDuration: 1) {
self.imageView.frame = CGRect(x: self.imageView.frame.origin.x, y: self.imageView.frame.origin.y, width: self.imageView.frame.width - 100, height: self.imageView.frame.height)
}
}
输出: