简体   繁体   English

如何在iOS上以编程方式将视图旋转180度?

[英]How to programmatically rotate the view by 180 degrees on iOS?

如何以编程方式在我的iPhone应用程序中将视图旋转180度?

As 'CGAffineTransformRotate' uses radians as its unit of measure, and 180 degrees is the same as PI, instead of the math provided in other answers you can simply do: 由于'CGAffineTransformRotate'使用弧度作为度量单位,180度与PI相同,而不是其他答案中提供的数学,您可以简单地做:

view.transform = CGAffineTransformRotate(view.transform, M_PI);

Swift 3: 斯威夫特3:

view.transform = view.transform.rotated(by: .pi)

If you plan on doing a lot of transforms, it's probably best to read up on radians, so you understand what is going on. 如果您计划进行大量的变换,最好是阅读弧度,这样您就可以了解正在发生的事情。

Should be possible by using CGAffineTransform 应该可以使用CGAffineTransform

Quote from this question , this should do the trick: 这个问题引用,这应该做的伎俩:

CGFloat radians = atan2f(yourView.transform.b, yourView.transform.a);
CGFloat degrees = radians * (180 / M_PI);
CGAffineTransform transform = CGAffineTransformMakeRotation((90 + degrees) * M_PI/180);
yourView.transform = transform;

简单方案:

view.transform = CGAffineTransformMakeRotation(degrees*M_PI/180);

In Swift 3 : 在Swift 3中:

let rotationDegrees =  180.0
let rotationAngle = CGFloat(rotationDegrees * M_PI / 180.0)
view.transform = CGAffineTransform(rotationAngle: rotationAngle)

Swift 4: 斯威夫特4:

self.view.transform = CGAffineTransform(rotationAngle: .pi);

And a COMMENT (I evidently don't have enough points to enter my comment on his/her answer) for Benjamin Mayo or vtcajones answer of: Benjamin Mayovtcajones的回答是:评论(我显然没有足够的观点对我/她的答案进行评论):

view.transform = view.transform.rotated(by: .pi)

This will work the first time, but the next time it is called it will rotate the view again, back to the original rotation, which is probably not what you want. 这将是第一次工作,但下次调用时它将再次旋转视图,回到原始旋转,这可能不是你想要的。 It would be safer to set the transform value exactly each time. 每次精确设置变换值会更安全。

Same outcome as @Manny's answer using a different function. 与@ Manny使用不同功能的答案相同。

 CGFloat degreesOfRotation = 180.0;
 view.transform = CGAffineTransformRotate(view.transform,
     degreesOfRotation * M_PI/180.0);

最新的Swift 3语法:

view.transform = view.transform.rotated(by: .pi)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM