【发布时间】:2020-04-21 04:26:50
【问题描述】:
我有一堆 UILabel,但下面的 UILabel (lastMessage) 只显示一行。它应该被尾部截断,但没有省略号意味着第二行根本不存在。此外,dateTime UILabel 也没有显示。这可能与我的自动布局约束有关吗?我的 UITableViewCell 代码:
let nameLabel = UILabel()
let lastMessage = UILabel()
let profileImageView = UIImageView(image: #imageLiteral(resourceName: "blankAvatar"))
let dateTime = UILabel()
required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
nameLabel.numberOfLines = 1
nameLabel.tintColor = .label
nameLabel.font = .boldSystemFont(ofSize: 18)
nameLabel.translatesAutoresizingMaskIntoConstraints = false
dateTime.numberOfLines = 1
dateTime.tintColor = .label
dateTime.text = "7:03"
dateTime.translatesAutoresizingMaskIntoConstraints = false
lastMessage.numberOfLines = 2
lastMessage.tintColor = .lightGray
lastMessage.lineBreakMode = .byTruncatingTail
lastMessage.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.cornerRadius = profileImageView.frame.size.width
profileImageView.clipsToBounds = true
profileImageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(profileImageView)
contentView.addSubview(nameLabel)
contentView.addSubview(lastMessage)
contentView.addSubview(dateTime)
contentView.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 3)
let lg = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
profileImageView.leadingAnchor.constraint(equalTo: lg.leadingAnchor),
profileImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
profileImageView.heightAnchor.constraint(equalToConstant: 50),
profileImageView.widthAnchor.constraint(equalToConstant: 50),
nameLabel.topAnchor.constraint(equalTo: lg.topAnchor),
nameLabel.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 6),
nameLabel.trailingAnchor.constraint(equalTo: dateTime.leadingAnchor),
nameLabel.bottomAnchor.constraint(equalTo: lastMessage.topAnchor, constant: 6),
dateTime.topAnchor.constraint(equalTo: lg.topAnchor),
dateTime.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
dateTime.bottomAnchor.constraint(equalTo: lastMessage.topAnchor),
lastMessage.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 6),
lastMessage.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
lastMessage.bottomAnchor.constraint(equalTo: lg.bottomAnchor)
])
}
这是在初始化中。谢谢!
编辑:UITableViewCell 不是问题。我已将表格嵌入到水平 UIScrollView (repo) 中,但表格的自动布局约束是顶部、前导、尾随和底部锚点。我将它切换为除了尾随锚之外的所有锚,以便我可以使用宽度锚来代替 view.bounds.width 的常量。
【问题讨论】:
-
添加你得到的结果截图
-
哦,抱歉,有一段时间@DilanAnuruddha 似乎还有其他一些令人困惑的因素在起作用......它目前在一个水平移动的 UIScrollView 中,但是当我删除滚动视图时,问题就消失了。 ..?我想让我进一步调试一下。
-
@Yoomama 请检查我的答案。
标签: swift uitableview autolayout uilabel