首页 > 解决方案 > 将右约束添加到具有可变宽度的两个标签

问题描述

我在视图中有两个相邻的 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

我面临的问题是,日期在最右边对齐,用户名占据了整个宽度。我希望它有所不同 - 用户名的标签与需要一样宽,并且日期占据了剩余的整个空间。

现在的情况

换句话说:我希望绿色标签缩短以适合文本,红色标签占据剩下的整个宽度,所以它们都彼此相邻但是当用户名太长时它会截断并且仍然显示整个日期标签。我该怎么办?

标签: swiftuilabelnslayoutconstraint

解决方案


你需要设置

内容拥抱优先

tousernameLabel高于 其他 , 也 设置

内容抗压性

commentDateLabel更高


推荐阅读