大家好,我遇到了一个奇怪的问题。我想在单击带有动画的按钮时增加 View 的宽度,这在我的情况下工作正常。我用来增加宽度的代码如下-
@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
})
}
请帮助我哪里出错了。
最佳答案
你可以简单地使用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)
}
}
输出:
关于ios - 使用动画减少 View 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41163117/