每次点击按钮时如何将UIButton旋转90度并跟踪每个旋转位置/角度?
这是我到目前为止的代码,但它只旋转一次:
@IBAction func gameButton(sender: AnyObject) {
UIView.animateWithDuration(0.05, animations: ({
self.gameButtonLabel.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
}))
}
答案 0 :(得分:23)
self.gameButtonLabel.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
应改为
// Swift 3 - Rotate the current transform by 90 degrees.
self.gameButtonLabel.transform = self.gameButtonLabel.transform.rotated(by: CGFloat(M_PI_2))
// OR
// Swift 2.2+ - Pass the current transform into the method so it will rotate it an extra 90 degrees.
self.gameButtonLabel.transform = CGAffineTransformRotate(self.gameButtonLabel.transform, CGFloat(M_PI_2))
使用CGAffineTransformMake...
,您可以创建全新的转换并覆盖按钮上已有的任何转换。由于您希望将90度附加到已存在的变换(可能已经旋转0度,90度等),您需要添加到当前变换。我给出的第二行代码就是这样做的。
答案 1 :(得分:8)
@IBOutlet weak var expandButton: UIButton!
var sectionIsExpanded: Bool = true {
didSet {
UIView.animate(withDuration: 0.25) {
if self.sectionIsExpanded {
self.expandButton.transform = CGAffineTransform.identity
} else {
self.expandButton.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2.0)
}
}
}
}
@IBAction func expandButtonTapped(_ sender: UIButton) {
sectionIsExpanded = !sectionIsExpanded
}