【发布时间】:2018-06-10 07:01:16
【问题描述】:
我正在用 Objective C 为 iOS 做一些业余爱好者编程,但在 Apple 过渡到 Swift 时就退出了。最近开始尝试学习 Swift,并拼凑了一个非常简单的应用程序来开始理解它。
我有一个以 UIView 和三个按钮开头的屏幕,如图所示。 “扩大”按钮旨在使视图 (redBox) 放大,而“缩小”按钮则相反。 “更改颜色”按钮将redBox 的背景颜色更改为随机颜色。所有更改都旨在使用UIView.animate(withDuration: 2, animations:进行动画处理
颜色变化有效,但缩放无效。希望有人能告诉我哪里出错了。
这是代码,感谢所有帮助:
import UIKit
import CoreGraphics
public extension UIColor {
public static var random: UIColor {
let max = CGFloat(UInt32.max)
let red = CGFloat(arc4random()) / max
let green = CGFloat(arc4random()) / max
let blue = CGFloat(arc4random()) / max
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
class ViewController: UIViewController {
@IBOutlet weak var redBox: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func growBox(_ sender: UIButton) {
UIView.animate(withDuration: 2, animations: {
self.redBox.transform.scaledBy(x: 1.1, y: 1.1)
},completion: nil)
}
@IBAction func shrinkIt(_ sender: UIButton) {
UIView.animate(withDuration: 2, animations: {
self.redBox.transform.scaledBy(x: 0.9, y: 0.9)
},completion: nil)
}
@IBAction func changeColor(_ sender: UIButton) {
UIView.animate(withDuration: 2, animations: {
self.redBox.backgroundColor = UIColor.random
}, completion: nil)
}
}
编辑 1:
根据下面的答案,我将转换代码更改为:
@IBAction func growBox(_ sender: UIButton) {
UIView.animate(withDuration: 2, animations: {
self.redBox.transform = self.redBox.transform.scaledBy(x: 1.05, y: 1.05)
},completion: nil)
}
@IBAction func shrinkIt(_ sender: UIButton) {
UIView.animate(withDuration: 2, animations: {
self.redBox.transform = self.redBox.transform.scaledBy(x: 0.95238, y: 0.95238)
},completion: nil)
}
虽然这似乎可行,但“收缩”变换会留下一些痕迹,如下所示:
有人知道这是什么意思吗?
【问题讨论】:
标签: ios swift animation uiview