ios - 如何旋转 iOS 标签并使其贴在屏幕边缘?

标签 ios swift xcode storyboard uikit

例如,我有以下结构:

Start

我想将我的标签旋转 270 度以实现此目的:

End

通过 CGAffineTransform.rotated 接下来的方式:

    credentialsView.text = "Developed in EVNE Developers"
    credentialsView.transform = credentialsView.transform.rotated(by: CGFloat(Double.pi / 2 * 3))

但我得到的不是预期结果:

enter image description here

那么,在不将其边界更改为正方形或其他任何操作的情况下旋转 View 并保持距屏幕边缘 16 像素的正确方法是什么?

我尝试了很多方法,包括扩展 UILabel 以直接在 Storyboard 中查看旋转,将 dat View 放在带前导的堆栈 View 中,但它也没有帮助,等等。

最佳答案

这是一个解决方案,可以将您的标签以适当的方式来回旋转到垂直-水平状态。在运行代码之前,在 Storyboard中为您的标签设置约束条件:前导到 16 并垂直居中。

现在检查一下:

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    // Your leading constraint from storyboard, initially set to 16
    @IBOutlet weak var leadingConstraint: NSLayoutConstraint!

    var isHorizontal: Bool = true
    var defaultLeftInset: CGFloat = 16.0

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .white
        label.text = "This is my label"
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapAction)))
    }

    @objc func tapAction() {
        if self.isHorizontal {
            // Here goes some magic
            // constraints do not depend on transform matrix, 
            // so we have to adjust a leading one to fit our requirements
            leadingConstraint.constant = defaultLeftInset - label.frame.width/2 + label.frame.height/2
            self.label.transform = CGAffineTransform(rotationAngle: .pi/2*3)
        }
        else {
            leadingConstraint.constant = defaultLeftInset
            self.label.transform = .identity
        }
        self.isHorizontal = !self.isHorizontal
    }
}

关于ios - 如何旋转 iOS 标签并使其贴在屏幕边缘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50268286/

相关文章:

iOS8 - 防止在呈现 viewController 时旋转

ios - 无法在 Interface Builder 中连接 IBOutlet

ios-copyWithZone :]: unrecognized selector sent to instance

ios - 从自定义模式弹出窗口呈现 View Controller

ios - 如何通过命令行将Xcode项目构建和部署到新的Apple的TestFlight

ios - 无法访问 dispatch_async : "Variable is not Assignable (missing _block type specifier)" 中的全局变量

swift - 抛出函数的返回值

ios - 键盘将我的手机推出屏幕

ios - 如何在 Interface Builder 中设置自动布局约束以使默认常量始终为 0?

swift - 如何让SKSpriteNode以向下的曲线下降