CustomCollectionView in Swift3 - MosaicCollectionViewLayout
Hi there,
I am a newbie to AsyncDisplayKit and I am using Swift3 to create ASCollectionNode inside the ASTableView. The goal is to achieve something like attached image (This is done using UIKit). TableView Scrolls Vertically and CollectionView scrolls horizontally inside TableView


I am able to code most of the ASTableView and embed ASCollectionNode inside the TableCellNode however, getting stuck with the layout. I followed some of the suggestions to use ASRatioLayoutSpec ... and the ASCollectionNode works great with singleRow of pictures.
class CollectionViewCell: ASCellNode {
var imageNode : ASImageNode?
required init(with image : UIImage) {
super.init()
self.imageNode = ASImageNode.init()
imageNode?.image = image;
self.addSubnode(self.imageNode!)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
var imageRatio: CGFloat = 0.5
if imageNode?.image != nil {
imageRatio = (imageNode?.image?.size.height)! / (imageNode?.image?.size.width)!
}
let imagePlace = ASRatioLayoutSpec.init(ratio: imageRatio, child: imageNode!)
let stackLayout = ASStackLayoutSpec.horizontal()
stackLayout.justifyContent = .start
stackLayout.alignItems = .start
stackLayout.flexShrink = true
stackLayout.setChildren([imagePlace])
return ASInsetLayoutSpec.init(insets: UIEdgeInsets.zero, child: stackLayout)
}
}
Once I increase number of rows, I get following result:

Any suggestions how to pack the layout better and not have spaces?
Thanks, Rajeev AsyncDisplayKit Version 1.9.91
TableViewCell Code
var collectionNode : ASCollectionNode?
// initialize inside init()
let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
layout.scrollDirection = UICollectionViewScrollDirection.horizontal
layout.minimumLineSpacing = 1.0
layout.minimumInteritemSpacing = 1.0
AspectRatioCollectionViewFlowLayout.init())
self.collectionNode = ASCollectionNode.init(collectionViewLayout: layout)
extension TableViewCell : ASCollectionDelegate, ASCollectionDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos.count
}
func collectionView(_ collectionView: ASCollectionView, nodeBlockForItemAt indexPath: IndexPath) -> ASCellNodeBlock {
let photo : Photo = self.photos[indexPath.item]
return {
return CollectionViewCell.init(with: photo.thumbnail!)
}
}
func collectionView(_ collectionView: ASCollectionView, constrainedSizeForNodeAt indexPath: IndexPath) -> ASSizeRange {
let photo : Photo = self.photos[indexPath.item]
let aspectRatio:CGFloat = (photo.image?.size.width)! / (photo.image?.size.height)!
let width : CGFloat = min((tableSize?.width)!, (tableSize?.height)!)
let w = ((width - 2 * BORDER - 2 * HORIZONTAL_BUFFER)/3)
let size = CGSize.init(width: w, height: w)
return ASSizeRange.init(min: CGSize.init(width: aspectRatio * size.height, height: size.height),
max: CGSize.init(width: aspectRatio * size.height, height: size.height))
}
}
Hi All,
Is there an alternate forum to seek technical help? Looks like most of the questions here are related to issues / enhancement requests.
Please advice. Rajeev
It looks like I have to implement something like MosaicCollectionViewLayout as it's done in the CustomCollectionView Example. I took the stab at converting the Objective-C to Swift3. Here is the Swift version.. I am not sure if I did it right.. self.collectionView!.numberOfSections is returning zero for me.
import Foundation
import UIKit
import AsyncDisplayKit
protocol MosaicCollectionViewLayoutDelegate: ASCommonCollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, layout: MosaicCollectionViewLayout, originalItemSizeAtIndexPath: IndexPath) -> CGSize
}
class MosaicCollectionViewLayout: UICollectionViewLayout {
var numberOfColumns: Uint
var columnSpacing: CGFloat
var sectionInset: UIEdgeInsets
var interItemSpacing: UIEdgeInsets
var headerHeight: CGFloat
var _columnHeights: NSMutableArray
var _itemAttributes: NSMutableArray
var _headerAttributes: NSMutableDictionary
var _allAttributes: NSMutableArray
required override init() {
self.numberOfColumns = 3
self.columnSpacing = 10.0
self.headerHeight = 44.0 //viewcontroller
self.sectionInset = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
self.interItemSpacing = UIEdgeInsetsMake(10.0, 0, 10.0, 0)
_itemAttributes = []
_columnHeights = []
_allAttributes = []
_headerAttributes = [:]
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public var delegate : MosaicCollectionViewLayoutDelegate?
override func prepare() {
super.prepare()
var top: CGFloat = 0
let numberOfSections: NSInteger = self.collectionView!.numberOfSections
for section in 0 ..< numberOfSections {
let numberOfItems = self.collectionView?.numberOfItems(inSection: section)
top += sectionInset.top
if (headerHeight > 0) {
let headerSize: CGSize = self._headerSizeForSection(section: section)
let attributes: UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes.init(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, with: NSIndexPath.init(row: 0, section: section) as IndexPath)
attributes.frame = CGRect.init(x: sectionInset.left, y: top, width: headerSize.width, height: headerSize.height)
_headerAttributes[section] = attributes
_allAttributes.add(attributes)
top = attributes.frame.maxY
}
_columnHeights.add([] as NSMutableArray)
for _ in 0 ..< numberOfColumns {
(self._columnHeights[section] as! NSMutableArray).add(top)
}
let columnWidth: CGFloat = self._columnWidthForSection(section: section)
_itemAttributes.add([] as NSMutableArray);
for idx in 0 ..< numberOfItems! {
let columnIndex: Int = self._shortestColumnIndexInSection(section: section)
let indexPath = IndexPath.init(item: idx, section: section)
let itemSize: CGSize = self._itemSizeAtIndexPath(indexPath: indexPath);
let xOffset: CGFloat = sectionInset.left + (columnWidth + columnSpacing) * CGFloat(columnIndex)
let yOffset: CGFloat = ((_columnHeights[section] as! NSMutableArray)[columnIndex] as! CGFloat)
let attributes: UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
attributes.frame = CGRect.init(x: xOffset, y: yOffset, width: itemSize.width, height: itemSize.height)
(_columnHeights[section] as! NSMutableArray)[columnIndex] = attributes.frame.maxY + interItemSpacing.bottom
(_itemAttributes[section] as! NSMutableArray).add(attributes)
_allAttributes.add(attributes)
}
let columnIndex: Int = self._tallestColumnIndexInSection(section: section)
top = ((_columnHeights[section] as! NSMutableArray)[columnIndex] as! CGFloat) - interItemSpacing.bottom + sectionInset.bottom
for idx in 0 ..< (_columnHeights[section] as! NSMutableArray).count {
(_columnHeights[section] as! NSMutableArray)[idx] = top
}
}
}
func layoutAttributesForElementsInRect(rect: CGRect) -> NSArray
{
let includedAttributes: NSMutableArray = []
// Slow search for small batches
for attributes in _allAttributes {
if ((attributes as AnyObject).frame.intersects(rect)) {
includedAttributes.add(attributes)
}
}
return includedAttributes;
}
func layoutAttributesForItemAtIndexPath(indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
{
if (indexPath.section >= _itemAttributes.count) {
return nil;
} else if (indexPath.item >= (_itemAttributes[indexPath.section] as! NSMutableArray).count) {
return nil;
}
return (_itemAttributes[indexPath.section] as! NSMutableArray)[indexPath.item] as? UICollectionViewLayoutAttributes
}
func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
{
if (elementKind == UICollectionElementKindSectionHeader) {
return _headerAttributes[indexPath.section] as? UICollectionViewLayoutAttributes;
}
return nil;
}
func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool
{
if (!(self.collectionView?.bounds.size.equalTo(newBounds.size))!) {
return true;
}
return false;
}
func _widthForSection (section: Int) -> CGFloat
{
return self.collectionView!.bounds.size.width - sectionInset.left - sectionInset.right;
}
func _columnWidthForSection(section: Int) -> CGFloat
{
return (self._widthForSection(section: section) - ((CGFloat(numberOfColumns - 1)) * columnSpacing)) / CGFloat(numberOfColumns)
}
func _itemSizeAtIndexPath(indexPath: IndexPath) -> CGSize
{
var size: CGSize = CGSize.init(width: self._columnWidthForSection(section: indexPath.section), height: 0)
let originalSize: CGSize = self.delegate!.collectionView(self.collectionView!, layout:self, originalItemSizeAtIndexPath:indexPath)
if (originalSize.height > 0 && originalSize.width > 0) {
size.height = originalSize.height / originalSize.width * size.width
}
return size
}
func _headerSizeForSection(section: Int) -> CGSize
{
return CGSize.init(width: self._widthForSection(section: section), height: headerHeight)
}
override var collectionViewContentSize: CGSize
{
let height: CGFloat = ((_columnHeights.lastObject as? NSMutableArray)!.firstObject as? CGFloat)!
return CGSize.init(width: self.collectionView!.bounds.size.width, height: height)
}
func _tallestColumnIndexInSection(section: Int) -> Int
{
var index: Int = 0;
var tallestHeight: CGFloat = 0;
let a = _columnHeights[section] as? NSMutableArray
a?.enumerateObjects({ (height, idx, stop) in
if ((height as! CGFloat) > tallestHeight) {
index = idx;
tallestHeight = height as! CGFloat
}
})
return index
}
func _shortestColumnIndexInSection(section: Int) -> Int
{
var index: Int = 0;
var shortestHeight: CGFloat = CGFloat.greatestFiniteMagnitude
let a = _columnHeights[section] as? NSMutableArray
a?.enumerateObjects({ (height, idx, stop) in
if ((height as! CGFloat) < shortestHeight) {
index = idx;
shortestHeight = height as! CGFloat
}
})
return index
}
}
class MosaicCollectionViewLayoutInspector: NSObject, ASCollectionViewLayoutInspecting
{
func collectionView(_ collectionView: ASCollectionView, constrainedSizeForNodeAt indexPath: IndexPath) -> ASSizeRange {
let layout: MosaicCollectionViewLayout = collectionView.collectionViewLayout as! MosaicCollectionViewLayout
return ASSizeRangeMake(CGSize.zero, layout._itemSizeAtIndexPath(indexPath: indexPath))
}
func collectionView(_ collectionView: ASCollectionView, constrainedSizeForSupplementaryNodeOfKind: String, at atIndexPath: IndexPath) -> ASSizeRange
{
let layout: MosaicCollectionViewLayout = collectionView.collectionViewLayout as! MosaicCollectionViewLayout
return ASSizeRange.init(min: CGSize.zero, max: layout._headerSizeForSection(section: atIndexPath.section))
}
/**
* Asks the inspector for the number of supplementary sections in the collection view for the given kind.
*/
func collectionView(_ collectionView: ASCollectionView, numberOfSectionsForSupplementaryNodeOfKind kind: String) -> Uint {
if (kind == UICollectionElementKindSectionHeader) {
return UInt((collectionView.asyncDataSource?.numberOfSections!(in: collectionView))!)
} else {
return 0
}
}
/**
* Asks the inspector for the number of supplementary views for the given kind in the specified section.
*/
func collectionView(_ collectionView: ASCollectionView, supplementaryNodesOfKind kind: String, inSection section: UInt) -> Uint {
if (kind == UICollectionElementKindSectionHeader) {
return 1
} else {
return 0
}
}
}
Attached is the complete project Swift3 version of CustomCollectionView Sample. I think I am close.. but can't figure out why number of sections are coming in as zero. I would really appreciate if someone can help me debug this.
Thanks, Rajeev