How to align cell to top by Flow Layout in CollectionView - ios

In this code I am trying to change the size of the first cell of the UICollectionView and the others with the same size but in the first row only one cell is coming out when I want two to come out:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
if indexPath.row == 0 {
return CGSize(width: collectionView.frame.width/1.5-2, height: collectionView.frame.width/1.5-2)
}
else {
return CGSize(width: collectionView.frame.width/3.0-3, height: collectionView.frame.width/3.0-3)
}
}
What I really want is this:

You need to implement an UICollectionViewLayout, I had called it FillingLayout, Note that you can adjust the number of columns and the size of your big cells with the delegate methods
Explanation
You need to add an Array to track your columns heigths and see what is the shortest column that is private var columsHeights : [CGFloat] = [] and you need also an array of (Int,Float) tuple to keep which spaces are available to be filled, I also added a method in the delegate to get the number of columns we want in the collection View and a method to know if a cell can be added or not in a position according their size.
Then if we want to add a cell we check if can be added if not, because the first column is filled we add the space corresponding to column2 in the avaiableSpaces array and when we add the next cell first we check if can be added in any available space if can be added we add and remove the available space.
here is the full code
import UIKit
protocol FillingLayoutDelegate: class {
func collectionView(_ collectionView:UICollectionView, sizeForViewAtIndexPath indexPath:IndexPath) -> Int
// Returns the amount of columns that have to display at that moment
func numberOfColumnsInCollectionView(collectionView:UICollectionView) ->Int
}
class FillingLayout: UICollectionViewLayout {
weak var delegate: FillingLayoutDelegate!
fileprivate var cellPadding: CGFloat = 10
fileprivate var cache = [UICollectionViewLayoutAttributes]()
fileprivate var contentHeight: CGFloat = 0
private var columsHeights : [CGFloat] = []
private var avaiableSpaces : [(Int,CGFloat)] = []
fileprivate var contentWidth: CGFloat {
guard let collectionView = collectionView else {
return 0
}
let insets = collectionView.contentInset
return collectionView.bounds.width - (insets.left + insets.right)
}
var columnsQuantity : Int{
get{
if(self.delegate != nil)
{
return (self.delegate?.numberOfColumnsInCollectionView(collectionView: self.collectionView!))!
}
return 0
}
}
//MARK: PRIVATE METHODS
private func shortestColumnIndex() -> Int{
var retVal : Int = 0
var shortestValue = MAXFLOAT
var i = 0
for columnHeight in columsHeights {
//debugPrint("Column Height: \(columnHeight) index: \(i)")
if(Float(columnHeight) < shortestValue)
{
shortestValue = Float(columnHeight)
retVal = i
}
i += 1
}
//debugPrint("shortest Column index: \(retVal)")
return retVal
}
//MARK: PRIVATE METHODS
private func largestColumnIndex() -> Int{
var retVal : Int = 0
var largestValue : Float = 0.0
var i = 0
for columnHeight in columsHeights {
//debugPrint("Column Height: \(columnHeight) index: \(i)")
if(Float(columnHeight) > largestValue)
{
largestValue = Float(columnHeight)
retVal = i
}
i += 1
}
//debugPrint("shortest Column index: \(retVal)")
return retVal
}
private func canUseBigColumnOnIndex(columnIndex:Int,size:Int) ->Bool
{
if(columnIndex < self.columnsQuantity - (size-1))
{
let firstColumnHeight = columsHeights[columnIndex]
for i in columnIndex..<columnIndex + size{
if(firstColumnHeight != columsHeights[i]) {
return false
}
}
return true
}
return false
}
override var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
override func prepare() {
// Check if cache is empty
guard cache.isEmpty == true, let collectionView = collectionView else {
return
}
// Set all column heights to 0
self.columsHeights = []
for _ in 0..<self.columnsQuantity {
self.columsHeights.append(0)
}
for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let viewSize: Int = delegate.collectionView(collectionView, sizeForViewAtIndexPath: indexPath)
let blockWidth = (contentWidth/CGFloat(columnsQuantity))
let width = blockWidth * CGFloat(viewSize)
let height = width
var columIndex = self.shortestColumnIndex()
var xOffset = (contentWidth/CGFloat(columnsQuantity)) * CGFloat(columIndex)
var yOffset = self.columsHeights[columIndex]
if(viewSize > 1){//Big Cell
if(!self.canUseBigColumnOnIndex(columnIndex: columIndex,size: viewSize)){
// Set column height
for i in columIndex..<columIndex + viewSize{
if(i < columnsQuantity){
self.avaiableSpaces.append((i,yOffset))
self.columsHeights[i] += blockWidth
}
}
// Set column height
yOffset = columsHeights[largestColumnIndex()]
xOffset = 0
columIndex = 0
}
for i in columIndex..<columIndex + viewSize{
if(i < columnsQuantity){
//current height
let currValue = self.columsHeights[i]
//new column height with the update
let newValue = yOffset + height
//space that will remaing in blank, this must be 0 if its ok
let remainder = (newValue - currValue) - CGFloat(viewSize) * blockWidth
if(remainder > 0) {
debugPrint("Its bigger remainder is \(remainder)")
//number of spaces to fill
let spacesTofillInColumn = Int(remainder/blockWidth)
//we need to add those spaces as avaiableSpaces
for j in 0..<spacesTofillInColumn {
self.avaiableSpaces.append((i,currValue + (CGFloat(j)*blockWidth)))
}
}
self.columsHeights[i] = yOffset + height
}
}
}else{
//if there is not avaiable space
if(self.avaiableSpaces.count == 0)
{
// Set column height
self.columsHeights[columIndex] += height
}else{//if there is some avaiable space
yOffset = self.avaiableSpaces.first!.1
xOffset = CGFloat(self.avaiableSpaces.first!.0) * width
self.avaiableSpaces.remove(at: 0)
}
}
print(width)
let frame = CGRect(x: xOffset, y: yOffset, width: width, height: height)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache.append(attributes)
contentHeight = max(contentHeight, frame.maxY)
}
}
func getNextCellSize(currentCell: Int, collectionView: UICollectionView) -> Int {
var nextViewSize = 0
if currentCell < (collectionView.numberOfItems(inSection: 0) - 1) {
nextViewSize = delegate.collectionView(collectionView, sizeForViewAtIndexPath: IndexPath(item: currentCell + 1, section: 0))
}
return nextViewSize
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
// Loop through the cache and look for items in the rect
for attributes in cache {
if attributes.frame.intersects(rect) {
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item]
}
}
UPDATED
You need to setup your viewController as FillingLayoutDelegate
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
// Do any additional setup after loading the view.
if let layout = self.collectionView.collectionViewLayout as? FillingLayout
{
layout.delegate = self
}
}
FillingLayoutDelegate implementation in your ViewController
extension ViewController: FillingLayoutDelegate{
func collectionView(_ collectionView:UICollectionView,sizeForViewAtIndexPath indexPath:IndexPath) ->Int{
if(indexPath.row == 0 || indexPath.row == 4)
{
return 2
}
if(indexPath.row == 5)
{
return 3
}
return 1
}
func numberOfColumnsInCollectionView(collectionView:UICollectionView) ->Int{
return 3
}
}
ScreenShot working

This is not an exact answer to your question, but maybe it will help you.
Here is a very good tutorial:
https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2
Item # 6 I handed over for myself:
// 6. Updates the collection view content height
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] = yOffset[column] + height
//Only for 2 columns
if yOffset[1] >= yOffset[0] {
column = 0
} else {
column = 1
}

Related

Pin Cells to Top of UICollectionView Edge

I have a horizontally scrolling uicollectionview. I dynamically change each cell's height based on the length of a subview uilabel text string. At the end, I set the uicollectionview height constraint to equal the longest cell height.
This result in a uicollectionview where each cell varies in height and prevents me from achieving my goal: get all cells' tops to align and be pinned to the top edge of the uicollectionview.
Is anyone able to lend a hand here? I understand I might have to create a custom layout for this, but have no clue where to start and could not find any references to instruct. Any guidance would be appreciated!
easy to do it with custom UICollectionViewLayout,
put it simple:
you just assign the frame of each item manually.
Notice the logic in func prepare()
The rest method are just common mode.
for variable item height, you can use a delegate to fetch the value.
enum CommonComponent: String {
case cell
case header
var kind: String {
switch self{
case .header:
return "UICollectionElementKindSectionHeader"
default:
return ""
}
}
}
protocol CustomLayoutProxy: AnyObject {
func getHeightFor(indexPath ip: IndexPath) -> CGFloat
}
class CustomLayout: UICollectionViewLayout {
weak var delegate: CustomLayoutProxy?
override public var collectionViewContentSize: CGSize {
CGSize(width: collectionViewWidth, height: contentHeight)
}
// MARK: - Properties
private var contentHeight = CGFloat.zero
private var cache = [CommonComponent: [IndexPath: UICollectionViewLayoutAttributes]]()
private var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
private var collectionViewHeight: CGFloat {
collectionView!.frame.height
}
private var collectionViewWidth: CGFloat {
collectionView!.frame.width
}
let maxItemSize = CGSize(width: 40, height: 40)
}
// MARK: - LAYOUT CORE PROCESS
extension CustomLayout{
override public func prepare() {
guard let collectionView = collectionView else {
return
}
prepareCache()
var cellX: CGFloat = 16
let countOne = collectionView.numberOfItems(inSection: 0)
let headerIP = IndexPath(item: 0, section: 0)
let headH: CGFloat = 58
let headerAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CommonComponent.header.kind, with: headerIP)
headerAttributes.frame = CGRect(x: 0, y: contentHeight, width: UI.std.width, height: headH)
cache[.header]?[headerIP] = headerAttributes
contentHeight += headH
for item in 0 ..< countOne{
let cellIndexPath = IndexPath(item: item, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: cellIndexPath)
var size = maxItemSize
if let h = delegate?.getHeightFor(indexPath: cellIndexPath){
size.height = h
}
attributes.frame = CGRect( x: cellX, y: contentHeight, width: size.width, height: size.height )
contentHeight += exceedUp(origin: &cellX, limit: collectionViewWidth)
cache[.cell]?[cellIndexPath] = attributes
}
contentHeight += (maxItemSize.height + 16)
}
private func prepareCache() {
contentHeight = 0
cache.removeAll(keepingCapacity: true)
cache[.cell] = [IndexPath: UICollectionViewLayoutAttributes]()
cache[.header] = [IndexPath: UICollectionViewLayoutAttributes]()
}
}
//MARK: - PROVIDING ATTRIBUTES TO THE COLLECTIONVIEW
extension CustomLayout{
public override func layoutAttributesForSupplementaryView(ofKind ComponentKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
switch ComponentKind {
case CommonComponent.header.kind:
return cache[.header]?[indexPath]
default:
return nil
}
}
override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[.cell]?[indexPath]
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let _ = collectionView else { return nil }
visibleLayoutAttributes.removeAll(keepingCapacity: true)
for (_, infos) in cache {
for (_, attributes) in infos {
attributes.transform = .identity
if attributes.frame.intersects(rect) {
visibleLayoutAttributes.append(attributes)
}
}
}
return visibleLayoutAttributes
}
func exceedUp(origin x: inout CGFloat, limit widthX: CGFloat) -> CGFloat{
var exceedH: CGFloat = 0
let lineSpacing: CGFloat = 20
let interitemSpacing: CGFloat = 16
let contentEdge = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
if x + maxItemSize.width * 2 + interitemSpacing + contentEdge.right < widthX + 1{
x += maxItemSize.width + interitemSpacing
}
else{
x = contentEdge.left
exceedH = (maxItemSize.height + lineSpacing)
}
return exceedH
}
}
For more example , you can check my github repo
BoxDengJZ/UICollectionViewLeftAlignedLayout
coyingcat/CardCollection

CollectionView Different sizes without any library

I'm trying to design a collection view, which layout changes as shown in attached image. Please help if anyone has idea about this design.
Thanks in advance
I need that type of layout for collection view without any library
You need to Create subclass of UICollectionViewLayout and need
override prepare method.
Calculate Frame of UICollectionViewLayoutAttributes and store it in
Cache dictionary.
implement layoutAttributesForElements and layoutAttributesForItem
methods using cache dictionary
Here is code Please check :
import UIKit
class MJCollectionLayout: UICollectionViewLayout {
fileprivate var cache = [IndexPath: UICollectionViewLayoutAttributes]()
fileprivate var cellPadding: CGFloat = 1
fileprivate var contentHeight: CGFloat = 0
var oldBound: CGRect!
fileprivate var contentWidth: CGFloat {
guard let collectionView = collectionView else {
return 0
}
let insets = collectionView.contentInset
return collectionView.bounds.width - (insets.left + insets.right)
}
override var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
override func prepare() {
super.prepare()
contentHeight = 0
cache.removeAll(keepingCapacity: true)
guard cache.isEmpty == true, let collectionView = collectionView else {
return
}
if collectionView.numberOfSections == 0 {
return
}
oldBound = self.collectionView?.bounds
for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let cellSize = self.getCellSize(index: item)
let origin = self.getOrigin(index: item)
let frame = CGRect(origin: origin, size: cellSize)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache[indexPath] = (attributes)
contentHeight = max(contentHeight, frame.maxY)
}
}
func getCellSize(index: Int) -> CGSize {
let col = index % 6
let width = contentWidth / 2.0
if col == 2 {
return CGSize.init(width: 2 * width, height: width)
}
if col == 4 {
return CGSize.init(width: width, height: 2 * width)
}
return CGSize.init(width: width, height: width)
}
func getOrigin(index: Int) -> CGPoint {
let col = index % 6
let multiplayer = index / 6
let width = contentWidth / 2.0
var y: CGFloat = 0.0
var x: CGFloat = 0.0
if col == 0 || col == 1 {
y = CGFloat(multiplayer) * (8.0 * width) + 0
}
if col == 2 {
y = CGFloat(multiplayer) * (8.0 * width) + width
}
if col == 3 || col == 4 {
y = CGFloat(multiplayer) * (8.0 * width) + (2.0 * width)
}
if col == 5 {
y = CGFloat(multiplayer) * (8.0 * width) + (3.0 * width)
}
if col == 0 || col == 2 || col == 3 || col == 5 {
x = 0.0
}
if col == 1 || col == 4 {
x = width
}
return CGPoint(x: x, y: y)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
// Loop through the cache and look for items in the rect
visibleLayoutAttributes = cache.values.filter({ (attributes) -> Bool in
return attributes.frame.intersects(rect)
})
print(visibleLayoutAttributes)
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
// print(cache[indexPath.item])
return cache[indexPath]
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if newBounds.width != oldBound?.width {
return true
}
return false
}
}

Center different height CollectionView items

I followed this tutorial: https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2
and came up with the following code.
My question is now, how I can center the items of my collection view. Every item has a different height. (I have vertical scrolling enabled.)
class DynamicLayout: UICollectionViewFlowLayout {
var delegate: DynamicLayoutDelegate?
var numberOfColumns = 2
fileprivate var cellPadding: CGFloat = 6
fileprivate var contentHeight: CGFloat = 0
var xOffset = 0
fileprivate var contentWidth: CGFloat {
guard let c = collectionView else { return 0 }
return c.bounds.width - (c.contentInset.left + c.contentInset.right)
}
fileprivate var cache = [UICollectionViewLayoutAttributes]()
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func prepare() {
guard cache.isEmpty == true, let collectionView = collectionView else { return }
// let columnWidth = contentWidth / CGFloat(numberOfColumns)
let columnWidth = CGFloat(310)
var xOffset = [CGFloat]()
for column in 0 ..< numberOfColumns {
xOffset.append(CGFloat(column) * columnWidth)
}
var column = 0
var yOffset = [CGFloat](repeating: 0, count: numberOfColumns)
// 3. Iterates through the list of items in the first section
for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
// 4. Asks the delegate for the height of the picture and the annotation and calculates the cell frame.
let cellHeight = delegate?.collectionView(collectionView, heightFor: indexPath)
let height = cellPadding * 2 + cellHeight!
let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height)
// let totalCellWidth = CGFloat(310 * numberOfColumns)
// let totalSpacingWidth = cellPadding * CGFloat(numberOfColumns - 1)
// let leftInset = (collectionView.frame.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
// let leftInset = collectionView.frame.width - 310 / 2
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
// 5. Creates an UICollectionViewLayoutItem with the frame and add it to the cache
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache.append(attributes)
// 6. Updates the collection view content height
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] = yOffset[column] + height
column = column < (numberOfColumns - 1) ? (column + 1) : 0
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
// Loop through the cache and look for items in the rect
for attributes in cache {
if attributes.frame.intersects(rect) {
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item] }
}
protocol DynamicLayoutDelegate: class {
func collectionView(_ collectionView:UICollectionView, heightFor indexPath:IndexPath) -> CGFloat
}
The problem is, that I don't want to have empty space below and above smaller cells.
Screenshot of the problem:

Custom collection view layout crashes

I've created a custom data grid. It's based on collection view with custom layout. The layout modifies the first section and row attributes making them sticky, so when the user scrolls other rows and sections should go under the sticky ones. The idea for this layout is not mine, I've just adopted it. (I can't give the credits for the real creator, in my research I found so many variations of the layout that I'm not sure which is the original one).
Unfortunately I'm facing a problem with it. I'm getting a crash when scrolling:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no
UICollectionViewLayoutAttributes instance for
-layoutAttributesForItemAtIndexPath:
Despite the message I think that the real problem is in layoutAttributesForElements method. I've read some threads with a similar problem, but the only working solution is to return all cached attributes, no matter of the passed rectangle. I just don't like quick and dirty solutions like this. I would really appreciate any ideas/solutions you can give me.
The whole project is here. However the most important is the layout so for convenience here it is:
class GridViewLayout: UICollectionViewLayout {
//MARK: - Setup
private var isInitialized: Bool = false
//MARK: - Attributes
var attributesList: [[UICollectionViewLayoutAttributes]] = []
//MARK: - Size
private static let defaultGridViewItemHeight: CGFloat = 47
private static let defaultGridViewItemWidth: CGFloat = 160
static let defaultGridViewRowHeaderWidth: CGFloat = 200
static let defaultGridViewColumnHeaderHeight: CGFloat = 80
static let defaultGridViewItemSize: CGSize =
CGSize(width: defaultGridViewItemWidth, height: defaultGridViewItemHeight)
// This is regular cell size
var itemSize: CGSize = defaultGridViewItemSize
// Row Header Size
var rowHeaderSize: CGSize =
CGSize(width: defaultGridViewRowHeaderWidth, height: defaultGridViewItemHeight)
// Column Header Size
var columnHeaderSize: CGSize =
CGSize(width: defaultGridViewItemWidth, height: defaultGridViewColumnHeaderHeight)
var contentSize : CGSize!
//MARK: - Layout
private var columnsCount: Int = 0
private var rowsCount: Int = 0
private var includesRowHeader: Bool = false
private var includesColumnHeader: Bool = false
override func prepare() {
super.prepare()
rowsCount = collectionView!.numberOfSections
if rowsCount == 0 { return }
columnsCount = collectionView!.numberOfItems(inSection: 0)
// make header row and header column sticky if needed
if self.attributesList.count > 0 {
for section in 0..<rowsCount {
for index in 0..<columnsCount {
if section != 0 && index != 0 {
continue
}
let attributes : UICollectionViewLayoutAttributes =
layoutAttributesForItem(at: IndexPath(forRow: section, inColumn: index))!
if includesColumnHeader && section == 0 {
var frame = attributes.frame
frame.origin.y = collectionView!.contentOffset.y
attributes.frame = frame
}
if includesRowHeader && index == 0 {
var frame = attributes.frame
frame.origin.x = collectionView!.contentOffset.x
attributes.frame = frame
}
}
}
return // no need for futher calculations
}
// Read once from delegate
if !isInitialized {
if let delegate = collectionView!.delegate as? UICollectionViewDelegateGridLayout {
// Calculate Item Sizes
let indexPath = IndexPath(forRow: 0, inColumn: 0)
let _itemSize = delegate.collectionView(collectionView!,
layout: self,
sizeForItemAt: indexPath)
let width = delegate.rowHeaderWidth(in: collectionView!,
layout: self)
let _rowHeaderSize = CGSize(width: width, height: _itemSize.height)
let height = delegate.columnHeaderHeight(in: collectionView!,
layout: self)
let _columnHeaderSize = CGSize(width: _itemSize.width, height: height)
if !__CGSizeEqualToSize(_itemSize, itemSize) {
itemSize = _itemSize
}
if !__CGSizeEqualToSize(_rowHeaderSize, rowHeaderSize) {
rowHeaderSize = _rowHeaderSize
}
if !__CGSizeEqualToSize(_columnHeaderSize, columnHeaderSize) {
columnHeaderSize = _columnHeaderSize
}
// Should enable sticky row and column headers
includesRowHeader = delegate.shouldIncludeHeaderRow(in: collectionView!)
includesColumnHeader = delegate.shouldIncludeHeaderColumn(in: collectionView!)
}
isInitialized = true
}
var column = 0
var xOffset : CGFloat = 0
var yOffset : CGFloat = 0
var contentWidth : CGFloat = 0
var contentHeight : CGFloat = 0
for section in 0..<rowsCount {
var sectionAttributes: [UICollectionViewLayoutAttributes] = []
for index in 0..<columnsCount {
var _itemSize: CGSize = .zero
switch (section, index) {
case (0, 0):
switch (includesRowHeader, includesColumnHeader) {
case (true, true):
_itemSize = CGSize(width: rowHeaderSize.width, height: columnHeaderSize.height)
case (false, true): _itemSize = columnHeaderSize
case (true, false): _itemSize = rowHeaderSize
default: _itemSize = itemSize
}
case (0, _):
if includesColumnHeader {
_itemSize = columnHeaderSize
} else {
_itemSize = itemSize
}
case (_, 0):
if includesRowHeader {
_itemSize = rowHeaderSize
} else {
_itemSize = itemSize
}
default: _itemSize = itemSize
}
let indexPath = IndexPath(forRow: section, inColumn: index)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(x: xOffset,
y: yOffset,
width: _itemSize.width,
height: _itemSize.height).integral
// allow others cells to go under
if section == 0 && index == 0 { // top-left cell
attributes.zIndex = 1024
} else if section == 0 || index == 0 {
attributes.zIndex = 1023 // any ohter header cell
}
// sticky part - probably just in case here
if includesColumnHeader && section == 0 {
var frame = attributes.frame
frame.origin.y = collectionView!.contentOffset.y
attributes.frame = frame
}
if includesRowHeader && index == 0 {
var frame = attributes.frame
frame.origin.x = collectionView!.contentOffset.x
attributes.frame = frame
}
sectionAttributes.append(attributes)
xOffset += _itemSize.width
column += 1
if column == columnsCount {
if xOffset > contentWidth {
contentWidth = xOffset
}
column = 0
xOffset = 0
yOffset += _itemSize.height
}
}
attributesList.append(sectionAttributes)
}
let attributes = self.attributesList.last!.last!
contentHeight = attributes.frame.origin.y + attributes.frame.size.height
self.contentSize = CGSize(width: contentWidth,
height: contentHeight)
}
override var collectionViewContentSize: CGSize {
return self.contentSize
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
var curLayoutAttribute: UICollectionViewLayoutAttributes? = nil
if indexPath.section < self.attributesList.count {
let sectionAttributes = self.attributesList[indexPath.section]
if indexPath.row < sectionAttributes.count {
curLayoutAttribute = sectionAttributes[indexPath.row]
}
}
return curLayoutAttribute
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes: [UICollectionViewLayoutAttributes] = []
for section in self.attributesList {
let filteredArray = section.filter({ (evaluatedObject) -> Bool in
return rect.intersects(evaluatedObject.frame)
})
attributes.append(contentsOf: filteredArray)
}
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
//MARK: - Moving
override func layoutAttributesForInteractivelyMovingItem(at indexPath: IndexPath,
withTargetPosition position: CGPoint) -> UICollectionViewLayoutAttributes {
guard let dest = super.layoutAttributesForItem(at: indexPath as IndexPath)?.copy() as? UICollectionViewLayoutAttributes else { return UICollectionViewLayoutAttributes() }
dest.transform = CGAffineTransform(scaleX: 1.4, y: 1.4)
dest.alpha = 0.8
dest.center = position
return dest
}
override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath],
withTargetPosition targetPosition: CGPoint,
previousIndexPaths: [IndexPath],
previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths,
withTargetPosition: targetPosition,
previousIndexPaths: previousIndexPaths,
previousPosition: previousPosition)
collectionView!.dataSource?.collectionView?(collectionView!,
moveItemAt: previousIndexPaths[0],
to: targetIndexPaths[0])
return context
}
}
Implement layoutAttributesForItemAtIndexPath. As per the documentation, "Subclasses must override this method and use it to return layout information for items in the collection view. ".
In my experience this method is normally not called when running in the simulator but can be called on the device. YMMV.

Swift CollectionView Custom Layout Cell spacing

I am following the GitHub source to implement CustomCollectionViewLayout, the problem is occurring when i add space between cells but the functions like minimumLineSpacingForSectionAtIndex and setting edge insets functions are not calling even the delegate has been set. Please let me know how can i set space between each column, since i need space of 15 after first column and space of 10 after other columns.
This is what i have achieved so far:
class DemoGraphicCollectionViewLayout: UICollectionViewLayout {
var numberOfColumns : Int = 0
var itemAttributes : NSMutableArray!
var itemsSize : NSMutableArray!
var contentSize : CGSize!
override func prepare() {
if self.collectionView?.numberOfSections == 0 {
return
}
if (self.itemAttributes != nil && self.itemAttributes.count > 0) {
for section in 0..<self.collectionView!.numberOfSections {
let numberOfItems : Int = self.collectionView!.numberOfItems(inSection: section)
for index in 0..<numberOfItems {
if section != 0 && index != 0 {
continue
}
let attributes : UICollectionViewLayoutAttributes = self.layoutAttributesForItem(at: IndexPath(item: index, section: section))
if section == 0 {
var frame = attributes.frame
frame.origin.y = self.collectionView!.contentOffset.y
attributes.frame = frame
}
if index == 0 {
var frame = attributes.frame
frame.origin.x = self.collectionView!.contentOffset.x
attributes.frame = frame
}
}
}
return
}
if (self.itemsSize == nil || self.itemsSize.count != numberOfColumns) {
self.calculateItemsSize()
}
var column = 0
var xOffset : CGFloat = 0
var yOffset : CGFloat = 0
var contentWidth : CGFloat = 0
var contentHeight : CGFloat = 0
numberOfColumns = (collectionView?.numberOfSections)!
for section in 0..<self.collectionView!.numberOfSections {
let sectionAttributes = NSMutableArray()
for index in 0..<numberOfColumns {
var itemSize = (self.itemsSize[index] as AnyObject).cgSizeValue
let indexPath = IndexPath(item: index, section: section)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(x: xOffset, y: yOffset, width: (itemSize?.width)!, height: (itemSize?.height)!).integral
if section == 0 {
itemSize = CGSize(width: 150, height: 30)
}
if section == 0 && index == 0 {
attributes.zIndex = 1024;
} else if section == 0 || index == 0 {
attributes.zIndex = 1023
}
if section == 0 {
var frame = attributes.frame
frame.origin.y = self.collectionView!.contentOffset.y
frame.size.height = 30
attributes.frame = frame
}
if index == 0 {
var frame = attributes.frame
frame.origin.x = self.collectionView!.contentOffset.x
attributes.frame = frame
}
sectionAttributes.add(attributes)
xOffset += (itemSize?.width)!
column += 1
if column == numberOfColumns {
if xOffset > contentWidth {
contentWidth = xOffset
}
column = 0
xOffset = 0
yOffset += (itemSize?.height)!
}
}
if (self.itemAttributes == nil) {
self.itemAttributes = NSMutableArray(capacity: self.collectionView!.numberOfSections)
}
self.itemAttributes .add(sectionAttributes)
}
let attributes : UICollectionViewLayoutAttributes = (self.itemAttributes.lastObject as AnyObject).lastObject as! UICollectionViewLayoutAttributes
contentHeight = attributes.frame.origin.y + attributes.frame.size.height
self.contentSize = CGSize(width: contentWidth, height: CGFloat(0))
}
override var collectionViewContentSize : CGSize {
return self.contentSize
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes {
let aa = self.itemAttributes[indexPath.section] as! NSMutableArray
return aa[indexPath.row] as! UICollectionViewLayoutAttributes
}
override func layoutAttributesForElements(in rect: CGRect) ->[UICollectionViewLayoutAttributes]? {
var attributes = [UICollectionViewLayoutAttributes]()
if let itemAttributes = self.itemAttributes as NSArray as? [[UICollectionViewLayoutAttributes]] {
for section in itemAttributes {
let filteredArray = section.filter {evaluatedObject in
return rect.intersects(evaluatedObject.frame)
}
attributes.append(contentsOf: filteredArray)
}
}
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
func sizeForItemWithColumnIndex(_ columnIndex: Int) -> CGSize {
return CGSize(width: 150, height: 130)
}
func calculateItemsSize() {
self.itemsSize = NSMutableArray(capacity: (collectionView?.numberOfSections)!)
for index in 0..<(collectionView?.numberOfSections)! {
self.itemsSize.add(NSValue(cgSize: self.sizeForItemWithColumnIndex(index)))
}
}
}
Try this code. you will only need to replace UIImageView Object with your custom View.
https://github.com/krishnads/KConfigurableCollectionViewDemo
Well, I have tested the code for third party library and i also face the similar issue i.e my delegate methods were not calling. While investigating the issue I found that:
Method minimumInteritemSpacingForSectionAt is a part of UICollectionViewDelegateFlowLayout which is used by the UICollectionViewFlowLayout. The CustomCollectionLayout is a subclass of UICollectionViewLayout and not UICollectionViewFlowLayout. Thats why the delegate methods are not called.
You have an opportunity to adjust the layout in prepare method as mentioned in the source link. Unfortunately i didn't get enough time to implement it but I hope you will find some solution.
Here I found this info

Resources