OK - couple things...
As I said in my comment, add subviews and constraints to the cell's .contentView
, not to the cell itself.
You do have a few mistakes in your constraints. You constrained the countryNameLabel.trailingAnchor
to self.leadingAnchor
... that should be .leadingAnchor
to .leadingAnchor
.
Your .bottomAnchor
constants should be negative.
If you want the labels' text to determine their widths, don't assign a .widthAnchor
.
Try replacing your init with this:
override init(frame: CGRect) {
countryNameLabel = UILabel()
countryUserCountLabel = UILabel()
super.init(frame: frame)
contentView.addSubview(countryNameLabel)
countryNameLabel.translatesAutoresizingMaskIntoConstraints = false
countryNameLabel.font = UIFont.boldSystemFont(ofSize: 13)
countryNameLabel.textColor = .white
contentView.addSubview(countryUserCountLabel)
countryUserCountLabel.translatesAutoresizingMaskIntoConstraints = false
countryUserCountLabel.font = UIFont.systemFont(ofSize: 13)
countryUserCountLabel.textColor = .white
NSLayoutConstraint.activate([
// needs to be .leadingAnchor to .leadingAnchor
//countryNameLabel.trailingAnchor.constraint(equalTo: self.leadingAnchor, constant: 5),
countryNameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5),
countryNameLabel.heightAnchor.constraint(equalToConstant: 30),
countryNameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 5),
countryNameLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5),
// if you want the label width to fit its text
// don't set the label's widthAnchor
//countryNameLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 0),
//countryNameLabel.widthAnchor.constraint(equalToConstant: 20),
countryUserCountLabel.leadingAnchor.constraint(equalTo: countryNameLabel.trailingAnchor, constant: 5),
countryUserCountLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 5),
countryUserCountLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5),
countryUserCountLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -5),
countryUserCountLabel.heightAnchor.constraint(equalToConstant: 30),
// if you want the label width to fit its text
// don't set the label's widthAnchor
//countryUserCountLabel.widthAnchor.constraint(equalToConstant: 40)
])
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…