Rotating a UIButton by 90 degrees every time the button is clicked

一个人想着一个人 提交于 2019-12-21 03:16:48

问题


How do you rotate a UIButton by 90 degrees each time the button is clicked and also keep track of each rotated position/angle?

Here is the code I have so far but it only rotates once:

@IBAction func gameButton(sender: AnyObject) {
    UIView.animateWithDuration(0.05, animations: ({
        self.gameButtonLabel.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
    }))
}

回答1:


self.gameButtonLabel.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))

Should be changed to

// 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))

With CGAffineTransformMake..., you create a brand new transform and overwrite any transform that was already on the button. Since you want to append 90 degrees to the transform that already exists (which could be 0, 90, etc degrees rotated already), you need to add to the current transform. The second line of code I gave will do that.




回答2:


Swift 4:

@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
}


来源:https://stackoverflow.com/questions/39045122/rotating-a-uibutton-by-90-degrees-every-time-the-button-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!