2017-01-11 2 views
0

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

+0

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

+1

Was passiert, wenn Sie '-16' für die richtige Constraint-Konstante verwenden? – vacawama

+0

@vacawama es funktioniert! Wie? – bruno

Antwort

1

Das Problem ist die Reihenfolge der Artikel im Zwang. Sie sagen derzeit, dass das Label 16 nach dem rechten Rand seiner Superview ist. Sie können entweder item und toItem in Ihrer rechten Einschränkung umschalten oder -16 als Konstante verwenden.

Also entweder das:

addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: titleLabel, attribute: .right, multiplier: 1, constant: 16)) 

oder dies:

addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -16)) 

arbeiten.

+1

Arbeitete wie ein Charme! – bruno