ios - 使用自动布局调整标签大小
问题描述
问题说明
我在 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)
解决方案
首先缺少一些关键的东西你忘了使用 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])
}
我试图将文本更新为字符数比以前更多的新文本,我工作得很好
推荐阅读
- python - 以 4:3 格式而不是 16:9 格式在 python 中拍照
- javascript - 正则表达式 - 可选的非捕获组不匹配
- python - 只能分析第一行数据,其余为 NaN。(Python、熊猫、谷歌 Colab)
- scala - 在scala中获取char编码信息
- sql - 子查询返回超过 1 个值。当子查询遵循 SQL Server 时,这是不允许的
- javascript - 按按钮复制组件
- php - 从laravel中的一句话中取一个词?
- asp.net-core - 如何通过 Swashbuckle 使 SwaggerUI 在 traefik 代理后面的 docker 容器中工作?
- json - 意外字符('-'(代码 45)):soapUI 上的预期空间分隔根级值错误
- python - VSCode Jupyter 在使用 Sympy + IPython.display 时挂断