问题描述
如何旋转 UIButton
和 UILabel
的文本?90度,180度.
注意:在将其标记为重复之前,我有意将我的问题建模为该问题的 Swift 版本:
的文档基本格式是 CGAffineTransform(rotationAngle: CGFloat)
其中 rotationAngle
是弧度,而不是度数.
一个完整的圆(360 度)有 2π 弧度.Swift 包含有用的常量 CGFloat.pi
.
CGFloat.pi
= π = 180 度CGFloat.pi/2
= π/2 = 90 度
自动布局:
自动布局不适用于旋转视图.(有关原因,请参阅 Frame vs Bounds.)这个问题可以通过创建自定义视图来解决.This answer 展示了如何为 UITextView
执行此操作,但对于标签或按钮.(请注意,您必须删除该答案中的 CGAffineTransformScale
行,因为您不需要镜像文本.)
相关
How can you rotate text for UIButton
and UILabel
? 90 degrees, 180 degrees.
Note: Before you mark this as a duplicate, I am intentionally modelling my question as a Swift version of this one: How can you rotate text for UIButton and UILabel in Objective-C?
I am putting my answer in a similar format to this answer.
Here is the original label:
Rotate 90 degrees clockwise:
yourLabelName.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
Rotate 180 degrees:
yourLabelName.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
Rotate 90 degrees counterclockwise:
yourLabelName.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
Do the same thing to rotate a button. Thankfully the touch events also get rotated so the button is still clickable in its new bounds without having to do anything extra.
yourButtonName.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
Notes:
Documentation for CGAffineTransform
The basic format is CGAffineTransform(rotationAngle: CGFloat)
where rotationAngle
is in radians, not degrees.
There are 2π radians in a full circle (360 degrees). Swift includes the useful constant CGFloat.pi
.
CGFloat.pi
= π = 180 degreesCGFloat.pi / 2
= π/2 = 90 degrees
Auto Layout:
Auto layout does not work with rotated views. (See Frame vs Bounds for an explanation why.) This problem can be solved by creating a custom view. This answer shows how to do it for a UITextView
, but it is the same basic concept for a label or button. (Note that you will have to remove the CGAffineTransformScale
line in that answer since you don't need to mirror the text.)
Related
- How to do transforms on a CALayer?
- How to apply multiple transforms in Swift
- CTM transforms vs Affine Transforms in iOS (for translate, rotate, scale)
这篇关于如何在 Swift 中旋转 UIButton 和 UILabel 的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!