如何在Swift中旋转UIButton和UILabel的文本? [英] How can you rotate text for UIButton and UILabel in Swift?

查看:184
本文介绍了如何在Swift中旋转UIButton和UILabel的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何旋转UIButtonUILabel的文本? 90度,180度.

How can you rotate text for UIButton and UILabel? 90 degrees, 180 degrees.

注意:在您将其标记为重复之前,我有意将我的问题建模为该问题的Swift版本:

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?

推荐答案

我将答案的格式与此答案.

这是原始标签:

顺时针旋转90度:

yourLabelName.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)

旋转180度:

yourLabelName.transform = CGAffineTransform(rotationAngle: CGFloat.pi)

逆时针旋转90度:

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)

注释:

CGAffineTransform

基本格式为CGAffineTransform(rotationAngle: CGFloat),其中rotationAngle以弧度而不是度为单位.

The basic format is CGAffineTransform(rotationAngle: CGFloat) where rotationAngle is in radians, not degrees.

一个完整的圆(360度)中有2π弧度. Swift包含有用的常量CGFloat.pi.

There are 2π radians in a full circle (360 degrees). Swift includes the useful constant CGFloat.pi.

  • CGFloat.pi =π= 180度
  • CGFloat.pi / 2 =π/2 = 90度
  • CGFloat.pi = π = 180 degrees
  • CGFloat.pi / 2 = π/2 = 90 degrees

自动版式:

自动布局不适用于旋转视图. (有关原因的说明,请参见 Frame vs Bounds .)可以通过创建自定义视图来解决此问题. 此答案显示了对于UITextView的操作方法,但这与标签或按钮的基本概念相同. (请注意,由于不需要镜像文本,因此您必须删除该答案中的CGAffineTransformScale行.)

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

相关

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆