Swift:你如何为UIButton和UILabel旋转文本? [英] Swift: How can you rotate text for UIButton and UILabel?
问题描述
如何为 UIButton
和 UILabel
旋转文字? 90度,180度
注意:在将此标记为重复之前,我故意将我的问题建模为此版本的Swift版本:的文档
基本格式是 CGAffineTransform(rotationAngle:CGFloat)
其中 rotationAngle
以弧度表示,而不是度数。
整圆(360度)有2π弧度。 Swift包含有用常量 CGFloat.pi
。
-
CGFloat.pi
=π= 180度 -
CGFloat.pi / 2
=π/ 2 = 90度
自动布局:
自动布局不适用于旋转视图。 (有关解释原因,请参阅框架与边界。)可以通过创建自定义视图来解决此问题。 此答案显示如何为 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: Objective C: How can you rotate text for UIButton and UILabel?
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旋转文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!