swift - 将右约束添加到具有可变宽度的两个标签
问题描述
我在视图中有两个相邻的 UILabel,我将在其中显示对帖子的评论,一个用于用户名,一个用于时间戳。我将时间戳转换为简单的格式,例如一小时前的“1h”,22分钟前的“22m”等。
这是我的两个标签:
var usernameLabel: UILabel = {
let usernameLabel = UILabel()
usernameLabel.numberOfLines = 1
usernameLabel.lineBreakMode = .byTruncatingTail
usernameLabel.font = UIFont.boldSystemFont(ofSize: 15)
usernameLabel.textColor = UIColor.darkGray
usernameLabel.translatesAutoresizingMaskIntoConstraints = false
usernameLabel.text = "Username"
usernameLabel.isUserInteractionEnabled = true
usernameLabel.isExclusiveTouch = false
usernameLabel.backgroundColor = .green
return usernameLabel
}()
var commentDateLabel: UILabel = {
let commentDateLabel = UILabel()
commentDateLabel.font = UIFont.systemFont(ofSize: 12)
commentDateLabel.textColor = UIColor.lightGray
commentDateLabel.translatesAutoresizingMaskIntoConstraints = false
commentDateLabel.backgroundColor = .red
return commentDateLabel
}()
我对它们都添加了约束,以确保它们适合我的视图,如下所示:
commentDateLabel.leftAnchor.constraint(equalTo: usernameLabel.rightAnchor, constant: 8).isActive = true
commentDateLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -16).isActive = true
usernameLabel.leftAnchor.constraint(equalTo: profilePictureImageView.rightAnchor, constant: 16).isActive = true
我面临的问题是,日期在最右边对齐,用户名占据了整个宽度。我希望它有所不同 - 用户名的标签与需要一样宽,并且日期占据了剩余的整个空间。
换句话说:我希望绿色标签缩短以适合文本,红色标签占据剩下的整个宽度,所以它们都彼此相邻但是当用户名太长时它会截断并且仍然显示整个日期标签。我该怎么办?
解决方案
你需要设置
内容拥抱优先
tousernameLabel
高于 其他 , 也 设置
内容抗压性
要commentDateLabel
更高
推荐阅读
- python - Dockerfile - python:无法打开文件'/usr/app/client.py':[Errno 2]没有这样的文件或目录
- node.js - MongoDB Node.js 客户端投影
- java - 如何使用 selenium java 提取 HTML 值?
- vue.js - Vue.js - 将响应属性添加到对象数组。适用于本地 json。从 API 获取时不起作用
- arrays - 如何通过firebase存储和列出Ionic 3数组
- java - 无法生成 JTable 及其数据的图像
- python - pytorch .stack .squeeze 后的最终形状
- java - 在 docker 容器内使用时通过 SQLCMD 的 MSSQL 数据库实例连接问题
- git - 将一些文件放入 Git 存储库,我已设置为忽略
- wordpress - WordPress - 主页索引