Collection - Tai-Kimura/SwiftJsonUI GitHub Wiki

Collection

class: SJUICollectionView inherites: UICollectionView

Platform Support

  • UIKit: Full support (All attributes available)
  • ⚠️ SwiftUI: Partial support
    • Basic collection rendering supported through List/LazyVGrid/LazyHGrid
    • Complex layouts may require custom implementation
    • Cell registration and delegation handled differently in SwiftUI
  • Jetpack Compose: Full support (Maps to LazyGrid with sections support)
  • Android XML: Maps to androidx.recyclerview.widget.RecyclerView

Attributes for Collection

attribute name UIKit SwiftUI Compose XML type in json details remarks
showsHorizontalScrollIndicator boolean scrollview.showsHorizontalScrollIndicator. Default is false
showsVerticalScrollIndicator boolean scrollview.showsVerticalScrollIndicator. Default is false
paging boolean scrollview.isPagingEnabled
horizontalScroll boolean Flow layout direction: horizontal when true
insets array/string Section insets. Array [top, left, bottom, right] or string "top|left|bottom|right"
insetHorizontal float Left and right section insets
insetVertical float Top and bottom section insets
columnSpacing float Minimum interitem spacing
lineSpacing float Minimum line spacing
contentInsetAdjustmentBehavior string Content inset adjustment: automatic, always, never, scrollableAxes
contentInsets array/string Content insets. Same format as insets
itemWeight float Weight factor for item sizing. Default is 1.0 UIKit, SwiftUI only
layout string Layout type: "vertical" "horizontal". Default is "vertical"
sections array Section-based configuration for SwiftUI/Compose (see below) SwiftUI (7.1.2+), Compose
items string/array Data source binding. In SwiftUI/Compose, binds to CollectionDataSource
cellClasses array Cell class definitions with className only UIKit, Compose (legacy)
headerClasses array Header class definitions with className and identifier UIKit, Compose
footerClasses array Footer class definitions with className and identifier UIKit, Compose

Properties for Collection

Static Properties

open class var viewClass: SJUICollectionView.Type

This property will be used to decide which class to inflate with createFromJSON method. You should define the view's class on this property when you create classes inheriting from SJUICollectionView.

Inherited Properties

SJUICollectionView inherits all properties from UICollectionView and SJUIView, including:

  • Layout management and flow layout configuration
  • Data source and delegate functionality
  • Cell registration and reuse system
  • Section management (headers, footers)
  • Scroll position and content management
  • Touch and gesture handling from SJUIView
  • Layout constraint management

Functions for Collection

Initializers

required public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout)
required public init?(coder aDecoder: NSCoder)

Custom initializers that properly set up the collection view with the specified layout.

Static Methods

public class func createFromJSON(attr: JSON, target: Any, views: inout [String: UIView]) -> SJUICollectionView

Factory method called when the collection view is created from JSON file. Override this method when you create classes inheriting from SJUICollectionView class.

open class func getCollectionViewLayout(attr: JSON) -> UICollectionViewLayout

Determines the collection view layout based on JSON attributes. Default implementation returns UICollectionViewFlowLayout object. Override this method to provide custom layout implementations.

open class func getCollectionViewFlowLayout(attr: JSON) -> UICollectionViewFlowLayout

Configures and returns a UICollectionViewFlowLayout based on JSON attributes. Called internally by getCollectionViewLayout method. Override this method to customize flow layout behavior and properties.

Automatic Cell Registration

SJUICollectionView automatically handles cell, header, and footer registration:

  • Cell Classes: Registers classes from cellClasses JSON array
  • Header Classes: Registers header classes from headerClasses JSON array
  • Footer Classes: Registers footer classes from footerClasses JSON array
  • Module Resolution: Uses bundle name as module prefix for proper class lookup
  • Identifier Mapping: Maps class names to reuse identifiers automatically

Data Source and Delegate Integration

SJUICollectionView provides automatic integration with UICollectionView protocols:

  • Automatic delegate assignment if target conforms to UICollectionViewDelegate
  • Automatic data source assignment if target conforms to UICollectionViewDataSource
  • Support for all standard collection view callbacks and methods
  • Configurable through setTargetAsDelegate and setTargetAsDataSource attributes

Layout Configuration

Advanced layout configuration through JSON attributes:

  • Flow Layout: Full support for UICollectionViewFlowLayout customization
  • Item Sizing: Configurable through itemWeight and automatic sizing
  • Spacing Control: Column and line spacing configuration
  • Inset Management: Flexible inset specification (string or array format)
  • Scroll Direction: Support for both horizontal and vertical scrolling

Related Classes

SJUICollectionViewCell

open class SJUICollectionViewCell: UICollectionViewCell, ViewHolder

Base class for collection view cells with view holder functionality.

  • public var _views: Dictionary<String, UIView> - View dictionary for easy access

SJUICollectionReusableView

open class SJUICollectionReusableView: UICollectionReusableView, ViewHolder

Base class for collection view headers and footers with view holder functionality.

  • public var _views: Dictionary<String, UIView> - View dictionary for easy access

SwiftUI-Specific Features (7.1.2+)

Sections Attribute

The sections attribute is available only in SwiftUI mode and provides section-based configuration:

{
  "type": "Collection",
  "items": "@{collectionData}",
  "sections": [
    {
      "header": "SectionHeaderView",
      "cell": "ProductCell", 
      "footer": "SectionFooterView",
      "columns": 3
    },
    {
      "cell": "CategoryCell",
      "columns": 2
    }
  ]
}

Each section object can contain:

  • header: View name for section header (optional)
  • cell: View name for cells in this section
  • footer: View name for section footer (optional)
  • columns: Number of columns for this section (overrides global columns attribute)

CollectionDataSource in SwiftUI

In SwiftUI mode, the items attribute binds to a CollectionDataSource object instead of a simple array:

// In your ViewModel
@Published var collectionData = CollectionDataSource()

// Setup sections with data
let section1 = CollectionDataSection()
section1.cells = ("ProductCell", productDataArray)
section1.numberOfColumns = 3

let section2 = CollectionDataSection()
section2.header = ("SectionHeader", ["title": "Categories"](/Tai-Kimura/SwiftJsonUI/wiki/"title":-"Categories"))
section2.cells = ("CategoryCell", categoryDataArray)
section2.numberOfColumns = 2

collectionData.sections = [section1, section2]

CollectionDataSection Structure:

class CollectionDataSection {
    var header: (viewName: String, data: [String: Any](/Tai-Kimura/SwiftJsonUI/wiki/String:-Any))?
    var cells: (viewName: String, data: [String: Any](/Tai-Kimura/SwiftJsonUI/wiki/String:-Any))?
    var footer: (viewName: String, data: [String: Any](/Tai-Kimura/SwiftJsonUI/wiki/String:-Any))?
    var numberOfColumns: Int = 2
}

This architecture allows:

  • Different cell types per section
  • Variable column counts per section
  • Section-specific headers and footers
  • Dynamic data binding with proper SwiftUI updates

UIKit vs SwiftUI Differences

UIKit-only attributes:

  • cellClasses: Cell registration array (UIKit uses class-based registration)
  • headerClasses: Header registration array
  • footerClasses: Footer registration array
  • itemSize: Fixed size configuration
  • estimatedItemSize: Self-sizing configuration

SwiftUI-only attributes:

  • sections: Section-based layout configuration
  • items binds to CollectionDataSource (not simple array)

Inherited Methods

SJUICollectionView inherits all methods from UICollectionView and SJUIView, including:

  • Cell management (dequeueReusableCell, cellForItem, etc.)
  • Section management (numberOfSections, numberOfItemsInSection, etc.)
  • Layout management (performBatchUpdates, reloadData, etc.)
  • Selection handling (selectItem, deselectItem, etc.)
  • Scroll management (scrollToItem, setContentOffset, etc.)
  • Touch and gesture handling from SJUIView
  • Layout constraint management

Jetpack Compose Support

Sections in Compose

KotlinJsonUI supports the sections attribute for advanced collection layouts:

{
  "type": "Collection",
  "items": "@{collectionData}",
  "sections": [
    {
      "cell": "ProductCell",
      "columns": 3
    },
    {
      "header": "CategoryHeader",
      "cell": "CategoryCell",
      "footer": "CategoryFooter",
      "columns": 2
    }
  ]
}

CollectionDataSource in Compose

Similar to SwiftUI, Compose uses CollectionDataSource for section-based data:

// Kotlin ViewModel
val collectionData = CollectionDataSource(
    sections = listOf(
        CollectionDataSection(
            cells = CollectionDataSection.CellData(
                viewName = "ProductCell",
                data = productList
            ),
            columns = 3
        ),
        CollectionDataSection(
            header = CollectionDataSection.HeaderFooterData(
                viewName = "CategoryHeader",
                data = headerData
            ),
            cells = CollectionDataSection.CellData(
                viewName = "CategoryCell",
                data = categoryList
            ),
            footer = CollectionDataSection.HeaderFooterData(
                viewName = "CategoryFooter",
                data = footerData
            ),
            columns = 2
        )
    )
)

LCM-Based Grid Layout

When sections have different column counts, KotlinJsonUI automatically calculates the Least Common Multiple (LCM) to create a unified grid that accommodates all sections properly. For example:

  • Section 1: 3 columns
  • Section 2: 2 columns
  • Grid: 6 columns (LCM of 3 and 2)
  • Section 1 items span 2 columns each (6/3)
  • Section 2 items span 3 columns each (6/2)