首页 > 解决方案 > 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)

}

虽然这似乎可行,但“收缩”变换会留下一些痕迹,如下所示:

在此处输入图像描述

有人知道这是什么意思吗?

标签: iosswiftanimationuiview

解决方案


您在这里犯的错误是您认为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)

推荐阅读