首页 > 解决方案 > 使用自动布局调整标签大小

问题描述

问题说明

我在 iOS 应用程序的绘图视图左侧有一个标签。我已经成功地将标签旋转了 90 度,如下图所示,使用以下部分中复制的代码:

在此处输入图像描述

但是,一旦我将文本更改为“速度(公里/小时):,标签就会变宽,如下所示:

在此处输入图像描述

布局

界面生成器中没有设置相关的约束。此处设置的唯一约束是: - 标签的垂直居中 - 绘图视图的右侧、顶部和底部边缘粘在视图的右侧、顶部和底部边缘

其余的在代码中设置

在此处输入图像描述

代码

func setup(speedArray: [Float32]) {

    //Convert speed to Km/h from m/s
    let speedArrayKMH = speedArray.map({$0*3.6})

    //Draw Chart
    //This only styles the chart (colors, user interaction, etc...
    //no code in this fuction that affects layout)
    setupSpeedChart(speedArray: speedArrayKMH)

    //
    //  Customise speed label
    //
    //Label text
    chartTitleLabel.textAlignment = .center
    //Text color
    self.chartTitleLabel.textColor = BoxTextColor
    //Rotate
    chartTitleLabel.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi/2))
    //Constrain
    let C1 = NSLayoutConstraint(item: chartTitleLabel, attribute: .leadingMargin, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
    let C2 = NSLayoutConstraint(item: chartTitleLabel, attribute: .trailingMargin, relatedBy: .equal, toItem: speedLineChart, attribute: .leading, multiplier: 1, constant: 0)

    NSLayoutConstraint.activate([C1, C2])

}

我试过的

我尝试了许多结构和尺寸组合,包括:

似乎没有任何效果

例如,为标签宽度添加以下约束会产生:

let C3 = NSLayoutConstraint(item: chartTitleLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 45)

在此处输入图像描述

标签: iosswiftautolayoutuikit

解决方案


首先缺少一些关键的东西你忘了使用 translateAutoReaizingMaskIntoConstraints

转到情节提要 选择您的标签 转到标签下的检查器 有自动收缩 将其设置为最小字体大小 将大小设置为 11

然后在视图中执行以下操作 didload

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    myLabel.text = "speed in km"
    myLabel.textAlignment = .center
    myLabel.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi/2))
    myLabel.translatesAutoresizingMaskIntoConstraints = false
    let c1 = NSLayoutConstraint(item: myLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200)
    let c2 = NSLayoutConstraint(item: myLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 60)

    let c3 = NSLayoutConstraint(item: myLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: -60)
    let c4 = NSLayoutConstraint(item: myLabel, attribute: .centerY, relatedBy: .equal, toItem: myImageView, attribute: .centerY, multiplier: 1, constant: 0)

    NSLayoutConstraint.activate([c1, c2, c3, c4])

}

我试图将文本更新为字符数比以前更多的新文本,我工作得很好

这是在更改文本之前 这是在更改文本之后


推荐阅读