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.
Related
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
I mean initially there is dummy data then data gets loaded.
I am using collection view for the EPG. I want to load the data dynamically and at the same time I want to set the collection view cell width dynamically.
For example please see the JIOTV app. I am trying to do same thing in my application.
Below is my code of the custom layout.
import UIKit
class CustomCollectionViewLayout: UICollectionViewLayout {
var numberOfColumns = 8
var shouldPinFirstColumn = true
var shouldPinFirstRow = true
var sectionNumber = 0
var itemAttributes = [[UICollectionViewLayoutAttributes]]()
var itemsSize = [CGSize]()
var contentSize: CGSize = .zero
var arr = [String]()
var generalArr = [[String]]()
var durationArr = [String]()
override func prepare() {
guard let collectionView = collectionView else {
return
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
numberOfColumns = appDelegate.timeArr.count//appDelegate.eventNameArr.count //appDelegate.multipleColumns
// print(numberOfColumns)
if appDelegate.generalArr.count > 0 {
durationArr = appDelegate.generalArr[0]
generalArr = appDelegate.generalArr
if collectionView.numberOfSections == 0 {
return
}
if itemAttributes.count != collectionView.numberOfSections {
generateItemAttributes(collectionView: collectionView)
return
}
for section in 0..<collectionView.numberOfSections {
for item in 0..<collectionView.numberOfItems(inSection: section) {
if section != 0 && item != 0 {
continue
}
let attributes = layoutAttributesForItem(at: IndexPath(item: item, section: section))!
if section == 0 {
var frame = attributes.frame
frame.origin.y = collectionView.contentOffset.y
attributes.frame = frame
}
if item == 0 {
var frame = attributes.frame
frame.origin.x = collectionView.contentOffset.x
attributes.frame = frame
}
}
}
}
}
override var collectionViewContentSize: CGSize
{
return contentSize
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return itemAttributes[indexPath.section][indexPath.row]
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes = [UICollectionViewLayoutAttributes]()
for section in itemAttributes {
let filteredArray = section.filter { obj -> Bool in
return rect.intersects(obj.frame)
}
attributes.append(contentsOf: filteredArray)
}
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
func convertHourtoMin(strTime : String) -> Int {
var components: Array = strTime.components(separatedBy: ":")
let hours = Int(components[0]) ?? 0
let minutes = Int(components[1]) ?? 0
let seconds = Int(components[2]) ?? 0
return ((hours * 60) + (minutes) + (seconds / 60))
}
}
// MARK: - Helpers
extension CustomCollectionViewLayout {
func generateItemAttributes(collectionView: UICollectionView) {
if itemsSize.count != numberOfColumns {
calculateItemSizes()
}
var column = 0
var xOffset: CGFloat = 0
var yOffset: CGFloat = 0
var contentWidth: CGFloat = 0
itemAttributes = []
for section in 0..<collectionView.numberOfSections {
var sectionAttributes: [UICollectionViewLayoutAttributes] = []
arr = generalArr[section]
// print("General Array : \(arr)")
// print("General Array count : \(arr.count)")
numberOfColumns = arr.count
durationArr = arr
let appDelegate = UIApplication.shared.delegate as! AppDelegate
for index in 0..<numberOfColumns {
var itemSize = itemsSize[index]
if numberOfColumns == appDelegate.timeArr.count {
itemSize = itemsSize[index]
}
else {
calculateItemSizes()
itemSize = itemsSize[index]
}
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 && index == 0 {
// First cell should be on top
attributes.zIndex = 1024
} else if section == 0 || index == 0 {
// First row/column should be above other cells
attributes.zIndex = 1023
}
// Below code with section == 0 and index till end
/* if section == 0 && 0 < numberOfColumns {
attributes.frame = CGRect(x: xOffset, y: yOffset, width: 100, height: 54).integral
}
*/
if section == 0 {
var frame = attributes.frame
frame.origin.y = collectionView.contentOffset.y
attributes.frame = frame
}
if 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 == numberOfColumns {
if xOffset > contentWidth {
contentWidth = xOffset
}
column = 0
xOffset = 0
yOffset += itemSize.height
}
}
itemAttributes.append(sectionAttributes)
}
if let attributes = itemAttributes.last?.last {
contentSize = CGSize(width: contentWidth, height: attributes.frame.maxY)
}
}
func calculateItemSizes() {
itemsSize = []
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if numberOfColumns == appDelegate.timeArr.count{
for index in 0..<numberOfColumns {
itemsSize.append(sizeForItemWithColumnIndexA(index))
}
}
else {
for index in 0..<numberOfColumns {
itemsSize.append(sizeForItemWithColumnIndex(index))
}
}
}
func sizeForItemWithColumnIndex(_ columnIndex: Int) -> CGSize {
var text: NSString
switch columnIndex {
case 0: return CGSize(width: 80, height: 40) //54
// case 0: return CGSize(width: 106, height: 54)
// case 1:
// text = "MMM-99"
default:
text = "Content"
//return CGSize(width: 100, height: 54)
// for Stringresult in durationArr[columnIndex]
// Below is code to make the cell dynamic
var width:Float = Float(convertHourtoMin(strTime: durationArr[columnIndex]))
var actualWidth:Float = Float((width / 60) * 200) // * 100
actualWidth = actualWidth + actualWidth
// print("Actual Width : \(actualWidth)")
return CGSize(width: Int(actualWidth), height: 40) // 54
//}
}
// let size: CGSize = text.size(withAttributes: [kCTFontAttributeName as NSAttributedStringKey: UIFont.systemFont(ofSize: 14.0)])
// let width: CGFloat = size.width + 16
return CGSize(width: 100, height: 54)
}
// Below method is for time row in EPG VIEW
func sizeForItemWithColumnIndexA(_ columnIndex: Int) -> CGSize {
var text: NSString
switch columnIndex {
case 0: return CGSize(width: 80, height: 25)
// case 0: return CGSize(width: 106, height: 54)
// case 1:
// text = "MMM-99"
default:
text = "Content"
return CGSize(width: 200, height: 25) // originally width : 100
// for Stringresult in durationArr[columnIndex]
// Below is code to make the cell dynamic
var width:Float = Float(convertHourtoMin(strTime: durationArr[columnIndex]))
var actualWidth:Float = Float((width / 60) * 100)
actualWidth = actualWidth + actualWidth
// print("Actual Width : \(actualWidth)")
return CGSize(width: Int(actualWidth), height: 54)
//}
}
// let size: CGSize = text.size(withAttributes: [kCTFontAttributeName as NSAttributedStringKey: UIFont.systemFont(ofSize: 14.0)])
// let width: CGFloat = size.width + 16
return CGSize(width: 100, height: 35)
}
}
Check this out
For an EPG you will basically need to calculate the size of the cell and also it's position for each program for each channel.
I'm trying to create a custom UICollectionViewFlowLayout where items can be displayed either vertically or horizontally (see below)
Vertical:
|S|S|S|
|1|4|7|
|2|5|8|
|3|6|9|
Horizontal:
|S|1|2|3|
|S|4|5|6|
|S|7|8|9|
However, I cannot seem to get the vertical layout to work properly. The horizontal layout works just fine but every time I want to use the vertical layout it just crashes with the following error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0x7ffcf597fa60> {length = 2, path = 1 - 6}'
When I use the same data and force it to use the horizontal layout it works just fine which leads me to believe I'm doing something wrong with the layout attributes.
My custom flow layout class:
import UIKit
class CustomCollectionViewLayout: UICollectionViewFlowLayout {
var horizontalInset = 0.0 as CGFloat
var verticalInset = 0.0 as CGFloat
var minimumItemWidth = 0.0 as CGFloat
var maximumItemWidth = 0.0 as CGFloat
var itemHeight = 0.0 as CGFloat
var itemWidth = 0.0 as CGFloat
var initialItemSizeSet: Bool = false
var _layoutAttributes = Dictionary<String, UICollectionViewLayoutAttributes>()
var _contentSize = CGSize.zero
var transposed: Bool
init(transposed: Bool) {
self.transposed = transposed
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepare() {
super.prepare()
_layoutAttributes = Dictionary<String, UICollectionViewLayoutAttributes>()
_layoutAttributes.removeAll()
let path = IndexPath(item: 0, section: 0)
let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, with: path)
let headerHeight = CGFloat(self.itemHeight / 4)
attributes.frame = CGRect(x: 0, y: 0, width: self.collectionView!.frame.size.width, height: headerHeight)
let headerKey = layoutKeyForHeaderAtIndexPath(path)
_layoutAttributes[headerKey] = attributes
let numberOfSections = (self.collectionView!.numberOfSections)-1
var yOffset = headerHeight
var xOffset = self.horizontalInset
var largestNumberOfItems = 0
for section in 0...numberOfSections {
let numberOfItems = self.collectionView!.numberOfItems(inSection: section)
if(numberOfItems > largestNumberOfItems){
largestNumberOfItems = numberOfItems
}
for item in 0...numberOfItems {
let indexPath = IndexPath(item: item, section: section)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
var itemSize = CGSize.zero
//Every cell has a fixed size
if(!initialItemSizeSet){
self.itemWidth = 75
self.itemHeight = 75
initialItemSizeSet = true
}
itemSize.width = itemWidth
itemSize.height = itemHeight
attributes.frame = CGRect(x: xOffset, y: yOffset, width: itemSize.width, height: itemSize.height).integral
print("Created frame with xOffset \(xOffset), yOffset \(yOffset), width \(itemSize.width) and height \(itemSize.height)")
let key = layoutKeyForIndexPath(indexPath)
print("Attached indexPath key: \(key)")
_layoutAttributes[key] = attributes
if transposed {
yOffset += itemSize.height
yOffset += self.verticalInset
}else {
xOffset += itemSize.width
xOffset += self.horizontalInset
}
}
//After going through all items in section, check if current section is not the last section
if !(section == numberOfSections) {
if transposed {
//Increase xOffset for correct horizontal placement
xOffset += self.horizontalInset
xOffset += self.itemWidth
//Reset yOffset for correct spacing between cells
yOffset = self.verticalInset
}else {
//Increase yOffset for correct vertical placement
yOffset += self.verticalInset
yOffset += self.itemHeight
//Reset xOffset for correct spacing between cells
xOffset = self.horizontalInset
}
print("Finished adding items in section \(section), xOffset: \(xOffset), yOffset: \(yOffset)")
}else{
if transposed {
yOffset = self.verticalInset
}else {
xOffset = self.horizontalInset
}
}
}
if transposed {
xOffset += self.itemWidth
}else {
yOffset += self.itemHeight
}
//Calculate size of content based on largest number of items in the sections
print("xOffset: \(xOffset), yOffset: \(yOffset)")
if transposed {
_contentSize = CGSize(width: xOffset + self.horizontalInset, height: (CGFloat(largestNumberOfItems) * (itemHeight + yOffset)))
}else {
_contentSize = CGSize(width: (CGFloat(largestNumberOfItems) * (itemWidth + xOffset)), height: yOffset + self.verticalInset)
}
print("content size :\(_contentSize)")
}
func changeItemSize(_ newWidth: CGFloat, newHeight: CGFloat){
self.itemHeight = newHeight
self.itemWidth = newWidth
}
func changeInset(_ newHorizontalInset: CGFloat, newVerticalInset: CGFloat){
self.horizontalInset = newHorizontalInset
self.verticalInset = newVerticalInset
}
func layoutKeyForIndexPath(_ indexPath : IndexPath) -> String {
return "\(indexPath.section)_\(indexPath.row)"
}
func layoutKeyForHeaderAtIndexPath(_ indexPath : IndexPath) -> String {
return "s_\(indexPath.section)_\(indexPath.row)"
}
override var collectionViewContentSize : CGSize {
return _contentSize
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let headerKey = layoutKeyForIndexPath(indexPath)
return _layoutAttributes[headerKey]
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let key = layoutKeyForIndexPath(indexPath)
return _layoutAttributes[key]
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let predicate = NSPredicate { [unowned self] (evaluatedObject, bindings) -> Bool in
let layoutAttribute = self._layoutAttributes[evaluatedObject as! String]
return rect.intersects(layoutAttribute!.frame)
}
let dict = _layoutAttributes as NSDictionary
let keys = dict.allKeys as NSArray
let matchingKeys = keys.filtered(using: predicate)
return dict.objects(forKeys: matchingKeys, notFoundMarker: NSNull()) as? [UICollectionViewLayoutAttributes]
}
}
So it turns out that the cause of the crash was me forgetting that the number of items returned by the collectionview's numberOfItems(inSection) was not zero-based. I didn't think to look there because the horizontal layout handled this inconsistency fine for some unknown reason.
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
}
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