CGAffineTransform恢复旋转方向

i6x*_*x86 2 swift swift3

我使用以下代码旋转360º一个UIButton:

self.btn.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(M_PI)) / 180.0)
    self.btn.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(M_PI)) / 180.0)
Run Code Online (Sandbox Code Playgroud)

问题是它从左向右旋转,我想反转方向.我尝试过使用-M_PI或-180等组合,但没有成功.我究竟做错了什么?

Dav*_* S. 11

您可以应用负变换来反转方向:

self.btn.transform = CGAffineTransform(rotationAngle: -0.999*CGFloat.pi)
Run Code Online (Sandbox Code Playgroud)

撤消它:

self.btn.transform = CGAffineTransform.identity
Run Code Online (Sandbox Code Playgroud)

请记住,变换会改变视图,但不会改变实际对象.您不必"撤消"它,只需将其替换即可.

这是一些简单的工作游乐场代码,逆时针显示动画:

import UIKit
import PlaygroundSupport

let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor.red
PlaygroundPage.current.liveView = view

let button = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))

button.backgroundColor = UIColor.white
view.addSubview(button)

UIView.animateKeyframes(withDuration: 2.0, delay: 0.0, options: .repeat, animations: {
    let rotation = -0.999*CGFloat.pi
    button.transform = CGAffineTransform(rotationAngle: rotation)
    print(rotation)
}, completion: nil)
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

动画