Swift + Autolayout:旋转 UILabel,将其放在 UIView 旁边 [英] Swift + Autolayout: Rotate UILabel, keep it next to UIView

查看:38
本文介绍了Swift + Autolayout:旋转 UILabel,将其放在 UIView 旁边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 UILabel 附加到另一个 UIView,目前使用 AutoLayout 布局.

I would like to have a UILabel attached to another UIView, currently layed out with AutoLayout.

我想实现的目标如下:

但是如果我只旋转视图,它会围绕中心点旋转,如果我改变锚点,上面的视图就会移动.如何首先使用自动布局布局两个视图,然后进行旋转?

But if I only rotate the view, it's rotated around the center point, and if I change the anchor point, the upper view moves. How do I have to layout the two views with autolayout first and then make the rotation?

目前,自动布局执行以下操作:

Currently, autolayout does the following:

使用以下代码:

    label.layer.anchorPoint = CGPoint(x: 0, y: 0)
    label.layer.transform = CATransform3DMakeRotation(CGFloat(-45 / 180.0 * CGFloat(M_PI)), 0, 0, 1)

我确实得到了类似的东西

I do get something like

推荐答案

不要改变锚点,因为那样会搞乱自动布局.

Don't change the anchor point, because that will mess up autolayout.

相反,在变换中补偿锚点的位置:

Instead, compensate for the anchor point's position in your transform:

class ViewController: UIViewController {

    @IBOutlet var label: UILabel!
    @IBOutlet var slider: UISlider!

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        updateTransform()
    }

    @IBAction func sliderValueChanged(_ sender: Any) {
        updateTransform()
    }

    private func updateTransform() {
        var transform = CGAffineTransform.identity
        let labelSize = label.bounds.size
        transform = transform.translatedBy(x: -labelSize.width / 2, y: labelSize.height / 2)
        transform = transform.rotated(by: -CGFloat(slider.value) * CGFloat.pi / 2)
        transform = transform.translatedBy(x: labelSize.width / 2, y: -labelSize.height / 2)
        label.transform = transform
    }

}

结果:

这篇关于Swift + Autolayout:旋转 UILabel,将其放在 UIView 旁边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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