coding for custom uicollectionview layout - ios

Where/How would I code for this cell layout behavior.
I need each cell to overlap the previous.
Cell 2 centerX is Cell 1 right edge and so forth...
What method would I override in my custom UICollectionViewLayout?

When creating a custom collectionView layout, override layoutAttributesForItem to configure cells layout behavior...
var preferredSize: CGSize? = CGSize(width: 100, height: 100)
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.size = preferredSize!
//Modifying the centerX property adjust the overlapping effect
let centerX = (preferredSize?.width)! / 2.0 + CGFloat(indexPath.item) * ((preferredSize?.width)! * 0.5 )
let centerY = collectionView!.bounds.height / 2.0
attributes.center = CGPoint(x: centerX, y: centerY)
attributes.zIndex = -(indexPath.item)
return attributes
}

Related

Swift - Facebook style image grid using UICollectionViewFlowLayout

I'm trying to implement Facebook style image layout in Swift. I found this SO question and followed the approach suggested by one of the answers. As a result, I almost achieved what I wanted to.
As you can see in the image above, however, there's an overflow: the three smaller cells seems to be taking up more than the screen width. However, if I subtract 0.1 to each of the cell's width, the problem seems to have been solved.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let item = indexPath.item
let width = collectionView.bounds.size.width
let padding:CGFloat = 5
if item < 2 {
let itemWidth:CGFloat = (width - padding) / 2.0
return CGSize(width: itemWidth, height: itemWidth)
} else {
let itemWidth:CGFloat = (width - 2 * padding) / 3.0
// let itemWidth:CGFloat = (width - 2 * padding) / 3.0 - 0.1 // This WORKS!!
return CGSize(width: itemWidth, height: itemWidth)
}
}
I guess the overflow is caused by the value of itemWidth rounding up. But I feel like subtracting a random hard-coded value is not the best practice when dealing with this kind of issue.
Can anyone suggest a better approach for this?
Below is the full code that is reproducible.
class ContentSizeCollectionView: UICollectionView {
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
}
class GridVC: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 5
layout.minimumInteritemSpacing = 5
let collectionView = ContentSizeCollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "ident")
return collectionView
}()
override func viewDidLoad() {
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let item = indexPath.item
let width = collectionView.bounds.size.width
let padding:CGFloat = 5
if item < 2 {
let itemWidth:CGFloat = (width - padding) / 2.0
return CGSize(width: itemWidth, height: itemWidth)
} else {
let itemWidth:CGFloat = (width - 2 * padding) / 3.0
return CGSize(width: itemWidth, height: itemWidth)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ident", for: indexPath)
cell.backgroundColor = .red
return cell
}
}
Update
floor((width - 2 * padding) / 3.0) did prevent the overflow, but it leaves a small gap at the end.
Change this line:
let itemWidth:CGFloat = (width - 2 * padding) / 3.0
to this:
let itemWidth:CGFloat = floor((width - 2 * padding) / 3.0)
You may want to do that with a 2 item row as well.
Edit
The initial problem is that floating-point numbers are approximations.
So, on an iPhone 8, for example, the view width is 375 points. The cell width calculation of:
let padding: CGFloat = 5
let itemWidth:CGFloat = (width - 2 * padding) / 3.0
itemWidth ends up being 121.666... (repeating), which UIKit interprets as 121.66666666666667.
So, 121.66666666666667 * 3.0 + 10 equals (roughly) 375.00000000000011 and... that is greater than 375.0.
So, the collection view says "can't fit that on one row."
Using floor() fixes the problem, except... it hits a really weird bug!
If you change numberOfItemsInSection from 5 to 8, you'll get two rows of 3, and there will be no gap on the right.
We can get around this by making the side cells slightly narrower than the center cell like this:
// we want all three to be the same heights
// 1/3 of (width - 2 * padding)
let itemHeight: CGFloat = (width - 2 * padding) / 3.0
// left and right cells will be 1/3 of (width - 2 * padding)
// rounded down to a whole number
let sideW: CGFloat = floor(itemHeight)
// center cell needs to be
// full-width minus 2 * padding
// minus
// side-width * 2
let centerW: CGFloat = (width - 2 * padding) - sideW * 2
// is it left (0), center (1) or right (2)
let n = (item - 2) % 3
// use the proper width value
let itemWidth: CGFloat = n == 1 ? centerW : sideW
return CGSize(width: itemWidth, height: itemHeight)
Or, what seems to be working is making the width just slightly smaller than the floating-point 1/3rd. You used -0.1, but it also works with:
let itemWidth:CGFloat = ((width - 2 * padding) / 3.0) - 0.0000001
In any case, that hopefully explains the reason for the "2 cells instead of 3" issue, and two options for avoiding it.

2 column collectionview sizing problem in some iphones

I am using this code
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let padding: CGFloat = 50
let collectionViewSize = collectionView.frame.size.width - padding
return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
}
I am able to get a 2 column collection view on all iPhones except iPhone X and iphone XR, I don't know why
How to force 2 columns for all iPhones?
You can set layout of your collectionView by creating new layout and set it's itemSize, minimumInteritemSpacing and minimumLineSpacing and then assign new layout as collectionView.collectionViewLayout:
func setCollectionViewLayout(withPadding padding: CGFloat) {
let layout = UICollectionViewFlowLayout()
let size = (collectionView.frame.width - padding) / 2
layout.itemSize = CGSize(width: size, height: size)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView.collectionViewLayout = layout
}
and then call this method in viewDidLayoutSubviews (this is moment when frames are loaded and you can calculate with collectionView's frame)
override func viewDidLayoutSubviews() {
setCollectionViewLayout(withPadding: 50)
}
Note: I would recommend you to set leading and trailing constraints of collectionView to constant 25 instead of using padding
I suggest that you calculate width according to safeAreaLayoytGuide and, if you're using UICollectionViewFlowLayout, sectionInset. For UICollectionViewFlowLayout the following code will calculate proper width:
let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
let width = collectionView.safeAreaLayoutGuide.layoutFrame.width
- sectionInset.left
- sectionInset.right
- collectionView.contentInset.left
- collectionView.contentInset.right
If you need two columns, than item width will be calculated like that:
let space: CGFloat = 10.0
let itemSize = CGSize(width: (width - space) / 2, height: 100 /*DESIRED HEIGHT*/)

How to properly size and center expanding cells in UICollectionView Swift 4.0

Note, I have scoured the internet and have not found a place to both size and centers cells that works. I tried doing it myself but I keep running to bugs I can't avoid. I am new to Swift. My code:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize {
let cellWidth = collectionView.frame.size.width / 7.0
let cellHeight = collectionView.frame.height - 4.0
let imageSideLength = cellWidth < cellHeight ? cellWidth : cellHeight
return CGSize(width: imageSideLength, height: imageSideLength)
}
//centers the cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
// Make sure that the number of items is worth the computing effort.
guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout,
let dataSourceCount = photoCollectionView.dataSource?.collectionView(photoCollectionView, numberOfItemsInSection: section),
dataSourceCount > 0 else {
return .zero
}
let cellCount = CGFloat(dataSourceCount)
let itemSpacing = flowLayout.minimumInteritemSpacing
let cellWidth = flowLayout.itemSize.width + itemSpacing
let cellHeight = flowLayout.itemSize.height
var insets = flowLayout.sectionInset
// Make sure to remove the last item spacing or it will
// miscalculate the actual total width.
let totalCellWidth = (cellWidth * cellCount) - itemSpacing
let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right
let contentHeight = collectionView.frame.size.height
// If the number of cells that exist take up less room than the
// collection view width, then center the content with the appropriate insets.
// Otherwise return the default layout inset.
guard totalCellWidth < contentWidth else {
return insets
}
// Calculate the right amount of padding to center the cells.
let padding = (contentWidth - totalCellWidth) / 2.0
insets.left = padding
insets.right = padding
insets.top = (contentHeight - cellHeight) / 2.0
//insets.bottom = (contentHeight - cellHeight) / 2.0
return insets
}
}
I try to use two separate functions: the first to size the cells and the second to center the cells. (Note I only want new cells to expand horizontally, with a maximum of 6 cells.) However, my calculation of cell height and width in the 2nd function does not agree with how I set it in the first function, setting off a chain of issues. Any insight on how to both size and center the cells such that I can have 1-6 cells horizontally fit on my screen centered would be great.
Your layout calls are conflicting. Try following THIS Tutorial to get the hang of it.
Otherwise a good answer for this is HERE
var flowLayout: UICollectionViewFlowLayout {
let _flowLayout = UICollectionViewFlowLayout()
// edit properties here
_flowLayout.itemSize = CGSize(width: 98, height: 134)
_flowLayout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5)
_flowLayout.scrollDirection = UICollectionViewScrollDirection.horizontal
_flowLayout.minimumInteritemSpacing = 0.0
// edit properties here
return _flowLayout
}
Set it with:
self.collectionView.collectionViewLayout = flowLayout // after initializing it another way
// or
UICollectionView(frame: .zero, collectionViewLayout: flowLayout)

Add a padding function in a tableView (Swift)

I would like to adjust this function (that was created originally for a collectionView)
let place = places[indexPath.row]
let annotationPadding = CGFloat(5)
let font = UIFont.systemFont(ofSize: 15)
let commentHeight = place.heightForComment(font, width: width)
let height = annotationPadding + commentHeight + annotationPadding
return height
So I can add it in func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { } in my tableView, how can I do? (My problem is that CGFloat do not accept width)
Assuming heightForComment for the collection view takes the width of the collection view cell, you can pass in the width of the table view, since table view cells are as wide as their containing table view:
let commentHeight = place.heightForComment(font, width: tableView.bounds.size.width)
If there is additional leading or trailing margins for the comment in the table view, you can subtract that from the table view width:
let commentHeight = place.heightForComment(font, width: tableView.bounds.size.width - (20 * 2)) // 20 points margin on left and right

iOS Swift 3: UICollectionView horizontal center and bigger cell

I want to build an collection view like this one:
Collection View
which has bigger cell at the center and cell is snapped to center of container view, but with Swift 3. I don't want to use library since I want to learn how to build a custom Collection View like this.
I've searched over SO but not found any appropriate solution yet
write that function
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: collectionView.frame.size.height)
}
make collection view [scroll Direction] Horizontal
and [scrolling] tick scrolling enable and paging enable
make cell biger
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let offSet = self.collectionView.contentOffset
let width = self.collectionView.bounds.size.width
let index = round(offSet.x / width)
let newPoint = CGPoint(x: index * size.width, y: offSet.y)
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in
},completion: {(UIVIewTransitionCoordinatorContext) in
self.collectionView.reloadData()
self.collectionView.setContentOffset(newPoint, animated: true)
})
}
To achieve this you will need to subclass UICollectionViewFlowLayout and override:
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
then call super.layoutAt... and alter the cell it returns via its .transform attribute and return your altered attributes
Here is an example I made previously.
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var att = super.layoutAttributesForElements(in: rect)!
if !(delegate?.reelPlayerFlowIsPreviewMode() ?? true) {
return att
}
let region = CGRect(x: (self.collectionView?.contentOffset.x)!,
y: (self.collectionView?.contentOffset.y)!,
width: (self.collectionView?.bounds.size.width)!,
height: (self.collectionView?.bounds.size.height)!)
let center = CGPoint(x: region.midX, y: region.midY)
for theCell in att {
print("\(theCell.indexPath.item)\n\(theCell)\n")
let cell = theCell.copy() as! UICollectionViewLayoutAttributes
var f = cell.frame
let cellCenter = CGPoint(x: f.midX, y: f.midY)
let realDistance = min(center.x - cellCenter.x, region.width)
let distance = abs(realDistance)
let d = (region.width - distance) / region.width
let p = (max(d, ReelPlayerFlowLayout.minPercent) * ReelPlayerFlowLayout.maxPercent)
f.origin.x += (realDistance * ((1 - ReelPlayerFlowLayout.maxPercent) + (ReelPlayerFlowLayout.maxPercent - ReelPlayerFlowLayout.minPercent)))
cell.frame = f
cell.size = CGSize (width: f.width * p, height: f.height * p)
let index = att.index(of: theCell)!
att[index] = cell
}
return att
}

Resources