Ich baue eine UICollectionViewCell-Schnittstelle nach Code. Alles funktioniert gut, außer der richtigen Einschränkung. Wenn ich die App starte, hat das Titeletikett von rechts eine Null. Hier ist mein CodeNSLayoutConstraint Rand null statt sechzehn
let titleLabel: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor.purple
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupViews() {
addSubview(titleLabel)
// titleLabel
// top constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 16))
// left constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 8))
// right constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 16))
// height constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 20))
}
Ich denke, es hat etwas mit toItem: self
zu tun hat, weil self
die uilabel
ist, und ich möchte im Zusammenhang den UICollectionViewCell
Wird die Zellengröße vor dem Hinzufügen von Unteransichten geladen? Falls nein, laden Sie die Zelle, führen Sie setupViews aus und führen Sie dann self.setNeedsDisplay(), self.layoutIfNeeded() aus. Wenn ja, können Sie auch versuchen, die obigen Funktionen auszuführen. – Starlord
Was passiert, wenn Sie '-16' für die richtige Constraint-Konstante verwenden? – vacawama
@vacawama es funktioniert! Wie? – bruno