我需要设置一个图像作为单元格的背景,所以:
第一次尝试:
- 将
UIImageView
放入单元格 - 设置约束的顶部、尾部、前导和底部为
superView
- 设置
imageView
内容模式为AspectFit
预期:图像拉伸以适应单元格自动大小,必须与UILabel
相同
实际:标签在顶部和一大堆空格,因为单元格是获取图像大小。
第二次尝试:
- remove bottom constraint from try 1
- get
self.bounds.size.height
- 设置图像
- 然后设置高度约束。
预期:图像之前,得到细胞高度图像主机,然后这个高度适用于图像。
实际:此时单元格没有任何设置,因此具有默认大小,图像小于实际单元格高度。
很多其他的尝试,但没有结果。
有谁知道如何实现这个吗?
好的-听起来问题是你的标签"垂直拉伸"。
要防止这种情况,请设置内容拥抱优先级:
topLabel.setContentHuggingPriority(.required, for: .vertical)
bottomLabel.setContentHuggingPriority(.required, for: .vertical)
这是一个完整的单元格类:
class AlexCell: UITableViewCell {
let topLabel: UILabel = {
let v = UILabel()
v.numberOfLines = 0
v.font = .systemFont(ofSize: 20.0, weight: .bold)
// don't let label expand vertically
v.setContentHuggingPriority(.required, for: .vertical)
return v
}()
let bottomLabel: UILabel = {
let v = UILabel()
v.numberOfLines = 0
v.font = .italicSystemFont(ofSize: 16.0)
// don't let label expand vertically
v.setContentHuggingPriority(.required, for: .vertical)
return v
}()
let imgView: UIImageView = {
let v = UIImageView()
// we want the image to COMPLETELY FILL the image view
v.contentMode = .scaleToFill
// or
//v.contentMode = .scaleAspectFill
return v
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
// add image view to contentView
imgView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(imgView)
// add labels to content view
topLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(topLabel)
bottomLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(bottomLabel)
// we'll use the default layout guide for margins
let g = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
// image view should fill the entire content view
imgView.topAnchor.constraint(equalTo: contentView.topAnchor),
imgView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
imgView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
imgView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
// top label top/leading/trailing to margins guide
topLabel.topAnchor.constraint(equalTo: g.topAnchor),
topLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor),
topLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor),
// bottom label top to top label bottom
bottomLabel.topAnchor.constraint(equalTo: topLabel.bottomAnchor, constant: 8.0),
// leading/trailing to margins guide
bottomLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor),
bottomLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor),
// bottom to margins guide
bottomLabel.bottomAnchor.constraint(equalTo: g.bottomAnchor),
])
}
}