2016-03-29 18 views
1

NSCollectionViewFlowLayoutは、右マージンに配置された項目を含むレイアウトを生成します。私はアラインメントオプションを期待していた。デリゲートでは、ドキュメント内に何も見つけられません。これを達成するには、NSCollectionViewFlowLayoutをサブクラス化する必要がありますか?ここでNSCollectionViewFlowLayout - 左揃え

答えて

8

は左詰めにフローレイアウトを作成するサブクラスです:

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

ここにバグがあります:! 'attributes.frame.origin.y場合= lastYPosition'は' attributes.frame.origin場合でなければなりませんが、新しい位置が最後の位置よりも小さいシナリオを防ぐために.y> lastYPosition'を使用します。これにより、UI要素が重なって描画されます。 (私の編集は拒否されました - この修正をコメントとして代わりに投稿しました) – gh123man

関連する問題