2016-03-29 11 views
1

NSCollectionViewFlowLayout erstellt ein Layout mit Elementen, die am rechten Rand ausgerichtet sind, oder, wenn der Container nur für einen Artikel breit genug ist, Objekte zentriert. Ich habe eine Ausrichtungsoption erwartet, z.B. auf dem Delegierten, aber finde nichts in den Dokumenten. Benötigt es die Unterklasse NSCollectionViewFlowLayout, um dies zu erreichen?NSCollectionViewFlowLayout - Linke Ausrichtung

Antwort

8

Hier ist eine Unterklasse, die eine linksbündige Flow Layout erzeugt:

class LeftFlowLayout: NSCollectionViewFlowLayout { 

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [NSCollectionViewLayoutAttributes] { 

     let defaultAttributes = super.layoutAttributesForElementsInRect(rect) 

     if defaultAttributes.isEmpty { 
      // we rely on 0th element being present, 
      // bail if missing (when there's no work to do anyway) 
      return defaultAttributes 
     } 

     var leftAlignedAttributes = [NSCollectionViewLayoutAttributes]() 

     var xCursor = self.sectionInset.left // left margin 

     // if/when there is a new row, we want to start at left margin 
     // the default FlowLayout will sometimes centre items, 
     // i.e. new rows do not always start at the left edge 

     var lastYPosition = defaultAttributes[0].frame.origin.y 

     for attributes in defaultAttributes { 
      if attributes.frame.origin.y != lastYPosition { 
       // we have changed line 
       xCursor = self.sectionInset.left 
       lastYPosition = attributes.frame.origin.y 
      } 

      attributes.frame.origin.x = xCursor 
      // by using the minimumInterimitemSpacing we no we'll never go 
      // beyond the right margin, so no further checks are required 
      xCursor += attributes.frame.size.width + minimumInteritemSpacing 

      leftAlignedAttributes.append(attributes) 
     } 
     return leftAlignedAttributes 
    } 
} 
+1

Es ist ein Fehler hier: 'wenn attributes.frame.origin.y = lastYPosition' sollte' sein, wenn attributes.frame.origin .y> lastYPosition', um ein Szenario zu vermeiden, in dem die neue Position kleiner als die letzte Position ist. Dadurch werden UI-Elemente überlappend gezeichnet. (meine Bearbeitung wurde abgelehnt - dieses Update wird stattdessen als Kommentar veröffentlicht) – gh123man