ASCollectionFlexLayout 1.2.0

ASCollectionFlexLayout 1.2.0

Suyeol Jeon 维护。



  • Suyeol Jeon

ASCollectionFlexLayout

ASCollectionFlexLayout 是一个自定义的集合布局,允许在 ASCollectionNode 中使用 Texture 布局规范。

screenshot

使用方法

创建布局

let layout = ASCollectionFlexLayout()
layout.layoutProvider = self

let collectionNode = ASCollectionNode(collectionViewLayout: layout)

如果没有指定 layoutProvider,将默认使用 ASStackLayout

实现 ASCollectionFlexLayoutProvider 协议

在 ASCollectionFlexLayout 中有两种布局规范。

  1. 用于区段的布局
  2. 用于区段内项目的布局

您可以可选地通过实现 ASCollectionFlexLayoutProvider 协议来提供每个布局规范。

protocol ASCollectionFlexLayoutProvider {
  /// A layout spec for sections. The default layout spec is a stretched stack layout with no spacing.
  func flexLayout(_ layout: ASCollectionFlexLayout, layoutSpecThatFits constrainedSize: ASSizeRange, sectionElements: [ASLayoutElement]) -> ASLayoutSpec?

  /// A layout spec for items in a section. The default layout spec is a flex-wrapping stack with no spacing.
  func flexLayout(_ layout: ASCollectionFlexLayout, layoutSpecThatFits constrainedSize: ASSizeRange, forSectionAt section: Int, itemElements: [ASLayoutElement]) -> ASLayoutSpec?
}

例如

extension MyViewController: ASCollectionFlexLayoutProvider {
  func flexLayout(_ layout: ASCollectionFlexLayout, layoutSpecThatFits constrainedSize: ASSizeRange, sectionElements: [ASLayoutElement]) -> ASLayoutSpec? {
    return ASStackLayoutSpec(
      direction: .vertical,
      spacing: 20,
      justifyContent: .start,
      alignItems: .start,
      children: sectionElements
    )
  }

  func flexLayout(_ layout: ASCollectionFlexLayout, layoutSpecThatFits constrainedSize: ASSizeRange, forSectionAt section: Int, itemElements: [ASLayoutElement]) -> ASLayoutSpec? {
    return ASStackLayoutSpec(
      direction: .horizontal,
      spacing: 10,
      justifyContent: .start,
      alignItems: .start,
      flexWrap: .wrap,
      alignContent: .start,
      lineSpacing: 10,
      children: itemElements
    )
  }
}

使用默认布局

您可以通过修改默认布局来应用布局,而无需实现ASCollectionFlexLayoutProvider协议。

let layout = ASCollectionFlexLayout()
layout.defaultSectionLayout.alignItems = .center
layout.defaultItemLayout.direction = .vertical
layout.defaultItemLayout.alignItems = .stretch

同样,您也可以直接在ASCollectionFlexLayoutProvider协议的实现中引用默认布局。

func flexLayout(_ layout: ASCollectionFlexLayout, layoutSpecThatFits constrainedSize: ASSizeRange, forSectionAt section: Int, itemElements: [ASLayoutElement]) -> ASLayoutSpec? {
  let insets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 20)
  return ASInsetLayoutSpec(insets: insets, child: layout.defaultItemLayout)
}

许可

ASCollectionFlexLayout遵循MIT许可。更多信息请参阅LICENSE