ios - UIView transform.scaleBy 动画不起作用
问题描述
我在 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)
}
虽然这似乎可行,但“收缩”变换会留下一些痕迹,如下所示:
有人知道这是什么意思吗?
解决方案
您在这里犯的错误是您认为scaledBy
会更改transform
属性。
它没有。Swift 中的方法名称实际上可以告诉您它们是否会改变调用它们的对象!看看它是如何命名的scaledBy
(用 a d
)而不是scaleBy
. 这表明此方法将返回一个已缩放的新转换。因为在英语中,你会这样说:
我希望这个视图的转换是这种特殊的转换,但是将 ***d*** 缩放 2 倍
在代码中你可以这样写:
thisView.transform = thisParticularTransformation.scaledBy(x: 2, y: 2)
这就是scaledBy
应该如何使用的。
如果要将视图的转换更改为绝对转换(与另一个转换无关),则需要创建一个新的CGAffineTransform
:
self.redBox.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
推荐阅读
- arrays - 为什么数组溢出在这里返回 0?
- apache - Magento 2 请求方法:POST 状态码:302
- python - 从 Pandas Dataframe 运行回归时,如何修复“ValueError:无法将字符串转换为浮点数”?
- typescript - 为什么脚本不在 jhipster 项目中运行?
- php - PHP (SQL) 中的网站语言翻译
- mysql - 在 Mysql/Sql 中。如何使一列将另一列的值作为默认值
- scala - 错误:值 orderBy 不是 org.apache.spark.sql.RelationalGroupedDataset 的成员
- exception - 为什么创建异常层次结构是更好的方法,而不是简单地在同一级别创建所有异常
- perl - 运行 perl 脚本时出现内存错误
- reactjs - ApolloLink 的 ApolloClient 类型错误