2016-06-07 23 views
1

Ich habe Probleme, das Layout einer Zelle anzupassen, wenn sich die horizontale Größenklasse ändert.Ändern des Zellenlayouts, wenn sich die Eigenschaft traitCollection ändert

Meine Zelle hat eine stackView und ich möchte die Achse für die horizontale Größenklasse Horizontal und Vertikale für Regular. Diese

ist, was ich versucht:

override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { 
    if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass { 
     self.collectionView?.reloadData() 
    } 
} 

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell 

    switch traitCollection.horizontalSizeClass { 
    case .Compact: 
     cell.stackView.axis = .Horizontal 
    default: 
     cell.stackView.axis = .Vertical 
    } 

    return cell 
} 

Aber das Ergebnis ist, dass nicht alle Zellen ihre Layout aktualisieren, SE gif unten.

EDIT: ich bestätigt habe, dass die Achse richtig selbst durch den Druck in cellForItem und in der Zellklasse geändert wird. So scheint die Frage zu sein, dass die Zellen nicht neu gezeichnet werden ..

Cell layout problems

Irgendwelche Vorschläge, wie ich dieses Problem lösen sollte?

Github Repo

+0

Implementieren Sie Ihre Reload in 'traitCollectionDidChange'. Wenn Sie 'willChange' tun, sehen Ihre Zellen immer noch die alte Merkmalssammlung http://stackoverflow.com/questions/24716136/where-to-update-autolayout-constraints-when-size-changes – Paulw11

+0

Danke, aber es hat immer noch nicht funktioniert. Wenn ich die 'traitCollection' in 'cellForItem' auslogge, wird sie aktualisiert, wenn ich auch willChange benutze, aber ich werde meine Frage mit deinem Vorschlag aktualisieren. – LarsJK

Antwort

2

einen Aufruf an layoutIfNeeded() zum cellForItemAtIndexPath Methode hinzufügen, um den Stapel Ansicht erhalten ihren Inhalt zu Neu-Layout:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell 

    switch traitCollection.horizontalSizeClass { 
    case .Compact: 
     cell.stackView.axis = .Horizontal 
    default: 
     cell.stackView.axis = .Vertical 
    } 

    cell.stackView.layoutIfNeeded() 

    return cell 
} 
+0

Vielen Dank! Das hat funktioniert. – LarsJK