Unexpected behavior with nested collection views with constraints (Swift 4) - ios

I have a cell in a tableview that contains a horizontal paging collection view.
Inside each page of this collection view there is a vertical collection view.
In order to avoid a "scroll-in-scroll" problem, I disabled vertical scrolling in the vertical collection views.
The vertical collection view's cell count is not static and can be any number.
So this creates a problem: the collection view (you'll have to ask me for clarification about which one) won't fit properly into the table view's cell anymore.
To solve this, I changed the table view's cell height by changing the constraints in the storyboard... but the problem remains.
Here is an image to help illustrate the problem:
and here is my code:
class myTBViewController: UITableViewController , UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView.tag == 10 {
return 2
} else {
return 30
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView.tag == 10 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mainPages", for: indexPath) as! mainPages
cell.backgroundColor = UIColor.yellow
cell.listCV.clipsToBounds = true
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "showAdvCell", for: indexPath) as! showAdvCell
cell.backgroundColor = UIColor.red
return cell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
if collectionView.tag == 10 {
let collectionViewHeight = collectionView.frame.height
let itemsHeight = collectionView.contentSize.height
let topInset = ( collectionViewHeight - itemsHeight ) / 4
return UIEdgeInsetsMake(topInset ,0, 0 , 0)
} else {
let collectionViewHeight = collectionView.frame.height
let itemsHeight = CGFloat(80)
let topInset = ( collectionViewHeight - itemsHeight ) / 4
return UIEdgeInsetsMake(topInset ,0, 0 , 0)
}
}
var headerSegment = UISegmentedControl()
override func viewDidLoad() {
super.viewDidLoad()
headerSegment.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width, height: 30)
let items = ["فروشگاه ها", "دیوار"]
headerSegment = UISegmentedControl(items: items)
headerSegment.selectedSegmentIndex = 0
headerSegment.addTarget(self, action: #selector(selectPage), for: UIControlEvents.valueChanged)
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200)
let headerImageView = UIImageView(frame: frame)
let image: UIImage = UIImage(named: "1")!
headerImageView.image = image
let frame3 = CGRect(x: 0, y: 0, width: 80, height: 80)
let headerImageView2 = UIImageView(frame: frame3)
let image2: UIImage = UIImage(named: "1")!
headerImageView2.image = image2
headerSegment.addSubview(headerImageView2)
headerSegment.bringSubview(toFront: headerImageView2)
headerImageView2.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 200)
headerSegment.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width + 10 , height: 40)
headerSegment.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 200)
let mainView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 230))
let headerSegmentView = UIView(frame : CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width, height: 40))
headerSegmentView.center = headerSegment.center
headerSegmentView.backgroundColor = UIColor.white
mainView.addSubview(headerImageView)
mainView.bringSubview(toFront: headerImageView)
mainView.addSubview(headerSegmentView)
mainView.bringSubview(toFront: headerSegmentView)
mainView.addSubview(headerSegment)
mainView.bringSubview(toFront: headerSegment)
mainView.addSubview(headerImageView2)
mainView.bringSubview(toFront: headerImageView2)
self.tableView.tableHeaderView = mainView
headerImageView2.layer.borderWidth = 2
headerImageView2.layer.masksToBounds = false
headerImageView2.layer.borderColor = UIColor.init(white: 255/255, alpha: 0.3).cgColor
headerImageView2.layer.cornerRadius = headerImageView2.frame.height/2
headerImageView2.clipsToBounds = true
}
#objc func selectPage() {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "myTBViewCell") as! myTBViewCell
switch headerSegment.selectedSegmentIndex {
case 0:
print("0")
cell.myTBCollectionView.scrollToItem(at:IndexPath(item: 0, section: 0), at: .top, animated: false)
case 1:
print("1")
cell.myTBCollectionView.scrollToItem(at:IndexPath(item: 1, section: 0), at: .top, animated: false)
default:
print("0")
cell.myTBCollectionView.scrollToItem(at:IndexPath(item: 0, section: 0), at: .top, animated: false)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
return 600
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "myTBViewCell", for: indexPath) as! myTBViewCell
return cell
}
}

I have a similar Problem , finally, I have solved it by creating a height Constraint of CollectionView.
than setting CollectionView height Constraint based on CollectionView ContentSize.
self.collectionViewHeight.constant = self.recentCollectionView.collectionViewLayout.collectionViewContentSize.height
the alternative approach is to override systemLayoutSizeFitting method of tableViewCell
ex:
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
self.tagCollectionView.layoutIfNeeded()
return self.tagCollectionView.collectionViewLayout.collectionViewContentSize
}
in addition you don't need to return fixed 600 height in your table view delegate heightForRowAtIndexPath

Related

Tableview section zerk while scroll using UIEdgeInsets

In my application I used parallax effect on tableview. So I used with UIEdgeInsets to show effect. It is perfect work without section but when I tried to with section it look ugly and section get zerk while scroll up and down. I have attached clip for more clearance. And I using bellow code. link Please help me
override func viewDidLoad()
{
super.viewDidLoad()
tblItemList.contentInset = UIEdgeInsets(top: 200, left: 0, bottom: 0, right: 0)
imageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 200)
imageView.image = UIImage.init(named: "32621859132_25f783b550_o.jpg")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
//imageView.backgroundColor = .white
view.addSubview(imageView)
}
extension RestaurantDetailsVC : UITableViewDataSource, UITableViewDelegate
{
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 105
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemSectionCell") as! ItemSectionCell
cell.backgroundColor = .white
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
//Scrollview delegate
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
let y = 200 - (scrollView.contentOffset.y + 200)
let height = min(max(y, 0), 300)
imageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: height)
if height <= 0
{
UIView.animate(withDuration: Double(0.1), animations: {
self.constraintTopForViewBar.constant = 0
self.viewForTopBar.isHidden = false
self.view.layoutIfNeeded()
}) { (result) in}
self.tblItemList.contentInset = UIEdgeInsets(top: 68, left: 0, bottom: 0, right: 0)
}
else
{
UIView.animate(withDuration: Double(0.1), animations: {
self.constraintTopForViewBar.constant = -68
self.viewForTopBar.isHidden = true
self.view.layoutIfNeeded()
}) { (result) in}
self.tblItemList.contentInset = UIEdgeInsets(top: 200, left: 0, bottom: 0, right: 0)
}
//print(height)
}
}

Configuring dynamic cell height with a custom collection view layout swift

I have a custom collection view layout which loads the cells from the bottom up for a messaging app, except I'm having trouble implementing dynamic cell heights. I believe the protocol and delegates I hooked up to retrieve the dynamic cell height are working for each cell (which I deduced from printing the height for each indexPath.item) except when the collectionView is loaded the cell heights are not the heights they are supposed to be. They are all just one static height (not the 80 preset by var cellHeight) and show just one line of text.
protocol InvertedStackProtocol: class {
func collectionView(_ collectionView: UICollectionView, heightForCellAtIndexPath indexPath: IndexPath) -> CGFloat
}
class InvertedStackLayout: UICollectionViewLayout, UICollectionViewDelegateFlowLayout {
var cellHeight: CGFloat = 80
weak var delegate: InvertedStackProtocol!
override func prepare() {
guard let collectionView = self.collectionView else {return}
for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let height = delegate.collectionView(collectionView, heightForCellAtIndexPath: indexPath)
print (height, indexPath.item)
cellHeight = height
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttrs = [UICollectionViewLayoutAttributes]()
if let collectionView = self.collectionView {
for section in 0 ..< collectionView.numberOfSections {
if let numberOfSectionItems = numberOfItemsInSection(section) {
for item in 0 ..< numberOfSectionItems {
let indexPath = IndexPath(item: item, section: section)
let layoutAttr = layoutAttributesForItem(at: indexPath)
if let layoutAttr = layoutAttr, layoutAttr.frame.intersects(rect) {
layoutAttrs.append(layoutAttr)
}
}
}
}
}
return layoutAttrs
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let layoutAttr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
let contentSize = self.collectionViewContentSize
layoutAttr.frame = CGRect(
x: 0, y: contentSize.height - CGFloat(indexPath.item + 1) * cellHeight,
width: contentSize.width, height: cellHeight)
return layoutAttr
}
func numberOfItemsInSection(_ section: Int) -> Int? {
if let collectionView = self.collectionView,
let numSectionItems = collectionView.dataSource?.collectionView(collectionView, numberOfItemsInSection: section)
{
return numSectionItems
}
return 0
}
override var collectionViewContentSize: CGSize {
get {
var height: CGFloat = 0.0
var bounds = CGRect.zero
if let collectionView = self.collectionView {
for section in 0 ..< collectionView.numberOfSections {
if let numItems = numberOfItemsInSection(section) {
height += CGFloat(numItems) * cellHeight
}
}
bounds = collectionView.bounds
}
return CGSize(width: bounds.width, height: max(height, bounds.height))
// return CGSize(width: bounds.width, height: height) do this for more exact fit of collection view
}
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if let oldBounds = self.collectionView?.bounds,
oldBounds.width != newBounds.width || oldBounds.height != newBounds.height
{
return true
}
return false
}
}
Use this method to change the height, UICollectionViewCell.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 125.0, height: 175.0)
}

Items in UICollectionView disappeared on scrolling

I have an UICollectionViewController which will be displayed both on its own full screen mode as well as in a pop-up view of another controller. The full screen mode works perfectly. However, in the pop-up mode, all items disappears after the user scroll the content up and down for a few times (sometimes more than 10 times, but also happen at the first or second time)
let vc = storyboard.instantiateViewController(
withIdentifier: "myCollectionView") as? MyColle ctionViewController
// set up the overlap in the parent controller
let bounds = CGRect(x: x + 22, y: parentFrame.origin.y + dy,
width: width, height: parentFrame.height - dy - 10)
overlayView = UIView(frame: bounds)
overlayView!.layer.cornerRadius = 5.0
overlayView!.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 0.4)
self.view.addSubview(overlayView!)
vc.showAsPopup(overlayView!)
// in MyCollectionViewController, add itself to the parent popup view
func showAsPopup(_ parentView: UIView) {
view.backgroundColor = UIColor.red // test color to show the view is never gone
view.layer.cornerRadius = 5.0
collectionView?.backgroundColor = UIColor.clear
collectionView?.layer.cornerRadius = 5.0
parentView.addSubview(view)
view.frame = CGRect(x: 0, y: 20,
width: parentView.frame.width,
height: parentView.frame.height - 20)
NSLog("my view bounds after: \(view.frame.origin.x) \(view.frame.origin.y)")
NSLog(" : \(view.frame.width)x\(view.frame.height)")
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
NSLog("\(items.count) items in section \(section)")
return items.count
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenRect = view.bounds
let scale = UIScreen.main.scale
let width = screenRect.size.width - 20
return CGSize(width: width, height: 45 * scale)
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = items[indexPath.item]
let cellId = "RCCell_\(item.id)"
NSLog("creating cell \(cellId)")
// Register cell classes
self.collectionView!.register(RemoteControlViewCell.self,
forCellWithReuseIdentifier: cellId)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId,
for: indexPath) as! RemoteControlViewCell
// Configure the cell, override the icon in Cell
cell.itemId = item.id
cell.itemIcon.image = item.icon
cell.itemDescriptionLabel.text = item.description
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 12.5, left: 0, bottom: 12.5, right: 0)
}
override func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
NSLog("removed cell at \(indexPath.row)")
}
// MyCollectionViewCell
override init(frame: CGRect) {
super.init(frame: frame)
let scale = UIScreen.main.scale
NSLog("Cell frame w: \(frame.size.width) h: \(frame.size.height), scale \(scale)")
let spacing = CGFloat(10)
contentView.backgroundColor = UIColor.white
contentView.layer.cornerRadius = 5
contentView.layer.masksToBounds = true
itemIcon = UIImageView(frame: CGRect(x: spacing, y: spacing,
width: CGFloat(24.0), height: CGFloat(24.0)))
itemIcon.contentMode = UIViewContentMode.scaleAspectFit
contentView.addSubview(itemIcon)
NSLog("icon w: \(itemIcon.frame.size.width)")
let labelX = spacing + 5 + itemIcon.frame.size.width
let font = UIFont.systemFont(ofSize: 20)
itemDescriptionLabel = UILabel(
frame: CGRect(x: labelX, y: spacing,
width: frame.size.width - labelX - spacing,
height: font.lineHeight))
itemDescriptionLabel.textColor = UIColor(colorLiteralRed: 0x66 / 255.0, green: 0x66 / 255.0, blue: 0x66 / 255.0, alpha: 1.0)
moduleDescriptionLabel.font = font
contentView.addSubview(itemDescriptionLabel)
NSLog("item desc \(String(describing: itemDescriptionLabel.text)) w: \(itemDescriptionLabel.frame.size.width)")
}
I tried changing the background color of the collectionView to visible and can see that the collect view itself was never gone even though the items disappeared. I also added logging to the collectionView() callback methods and found that they were never called again after the initial view presentation.
What could cause the items to disappear during scrolling?
Try using prepareForReuse in RemoteControlViewCell class
override func prepareForReuse() {
itemId = ""
itemIcon.image = nil
itemDescriptionLabel.text = ""
}

Swift How to get the centre cell in a collectionView and resize it when scrolling?

I have a horizontal collectionView and i would like to manage that when scrolling it, the centre cell becomes larger. So, each time a cell is the center cell it will be larger than the others. Check the image beneath.
Can anyone help me with the best way to do this? Thanks in advance!
My code so far:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet var horizontalCollectionView: UICollectionView!
#IBOutlet var verticalCollectionView: UICollectionView!
var horizontal = ["1","2","3","4","5","6","7","8","9","10","1","2","3","4","5","6","7","8","9","10"]
var horizontalCellSize = CGSize(width: 50, height: 50)
var horizontalLargeCellSize = CGSize(width: 80, height: 80)
var centerCell = UICollectionViewCell()
var cellIsInCenter = false
var myIndexPath = IndexPath()
override func viewDidLoad() {
super.viewDidLoad()
}
// When the main view's dimensions change this will re-layout the collection view
override func viewWillLayoutSubviews() {
verticalCollectionView.collectionViewLayout.invalidateLayout()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return horizontal.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == horizontalCollectionView {
let horizontalCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HorizontalCell", for: indexPath) as! HorizontalCell
horizontalCell.backgroundColor = UIColor.blue
horizontalCell.textLabel.text = horizontal[indexPath.row]
return horizontalCell
}
else {
let verticalCell = collectionView.dequeueReusableCell(withReuseIdentifier: "VerticalCell", for: indexPath) as! VerticalCell
verticalCell.backgroundColor = UIColor.red
verticalCell.textLabel.text = horizontal[indexPath.row]
return verticalCell
}
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self.horizontalCollectionView {
let horizontalScrollPosition = scrollView.contentOffset.x * 35
self.verticalCollectionView.delegate = nil
self.verticalCollectionView.contentOffset = CGPoint(x: 0, y: horizontalScrollPosition)
self.verticalCollectionView.delegate = self
}
if scrollView == self.verticalCollectionView {
let verticalScrollPosition = scrollView.contentOffset.y
self.horizontalCollectionView.delegate = nil
self.horizontalCollectionView.contentOffset = CGPoint(x: verticalScrollPosition, y: 0)
self.horizontalCollectionView.delegate = self
}
}
// MARK: CollectionViewLayout
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if collectionView == verticalCollectionView {
let size = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height)
return size
}
if indexPath.item == 3 {
return CGSize(width: 70, height: 70)
}
return CGSize(width: 50, height: 50)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.verticalCollectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
print("\(indexPath)")
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
var closestCell: UICollectionViewCell = self.horizontalCollectionView.visibleCells[0]
for cell in self.horizontalCollectionView.visibleCells as [UICollectionViewCell] {
let closestCellDelta = abs(closestCell.center.x - self.horizontalCollectionView.bounds.size.width / 2.0 - self.horizontalCollectionView.contentOffset.x)
let cellDelta = abs(cell.center.x - self.horizontalCollectionView.bounds.size.width/2.0 - self.horizontalCollectionView.contentOffset.x)
if (cellDelta < closestCellDelta){
closestCell = cell
self.centerCell = cell
self.cellIsInCenter = true
horizontalCellSize = CGSize(width: 80, height: 50)
}
}
let indexPath = self.horizontalCollectionView.indexPath(for: closestCell)
self.horizontalCollectionView.scrollToItem(at: indexPath!, at: .centeredHorizontally , animated: true)
if closestCell.backgroundColor == UIColor.black {
closestCell.backgroundColor = UIColor.blue
}
horizontalCollectionView.reloadItems(at: [self.horizontalCollectionView.indexPath(for: closestCell)!])
closestCell.backgroundColor = UIColor.black
}
}
Try this out:
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if collectionView == verticalCollectionView {
let size = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height)
return size
}
let point = CGPoint(x: self.view.frame.size.width/2.0, y:35 )
//or you can try this code also
//let point = CGPoint(x: UIScreen.main.bounds.width/2, y:35 )
print(point)
let centerIndex = self.collectionView.indexPathForItemAtPoint(point)
if indexPath.item == centerIndex {
return CGSize(width: 70, height: 70)
}
return CGSize(width: 50, height: 50)
}
This code gives you the index of the item at the center of the collection View.
Hope this helps

Embedding images from array in cells of Collection view

I have a UIViewController setup that also contains a UICollectionView inside of it. This Collection view has multiple cells, each of which I would like to make display an image. The images are contained in an array called imageThumbsAray. Each cell is a 90x90 square and I would like the image to fill the content area of each cell. Below is my code for the collection view. It seems to be correct, but when I run the app, I am returned with an empty collection view.
func SetupCollectionView() {
let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 90, height: 90)
PastObjectsCollection = UICollectionView(frame: CGRect(x: 16, y: 229, width: 368, height: 368), collectionViewLayout: layout)
PastObjectsCollection!.dataSource = self
PastObjectsCollection!.delegate = self
PastObjectsCollection!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier:"Chow Object Reuse ID")
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return objectsCount
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Chow Object Reuse ID", forIndexPath: indexPath) as UICollectionViewCell
cell.backgroundColor = UIColor.whiteColor()
var imageView:UIImageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: 90, height: 90)
imageView.image = imageThumbsArray[indexPath.row]
cell.addSubview(imageView)
return cell
}
Why is the Collection view not creating the cells?
Thanks,
Siddharth
This code use as much of your code as as I could. You can compare line by line. I did't have your image assets or object array. This is all programmatic. Let me know if you need more help.
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var PastObjectsCollection:UICollectionView?
var layout:UICollectionViewFlowLayout?
override func viewDidLoad() {
super.viewDidLoad()
SetupCollectionView()
}
func SetupCollectionView() {
self.layout = UICollectionViewFlowLayout()
self.layout!.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
self.layout!.itemSize = CGSize(width: 90, height: 90)
self.PastObjectsCollection = UICollectionView(frame: CGRect(x: 16, y: 229, width: 368, height: 368), collectionViewLayout: layout!)
self.PastObjectsCollection!.dataSource = self
self.PastObjectsCollection!.delegate = self
self.PastObjectsCollection!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier:"Chow Object Reuse ID")
self.PastObjectsCollection!.backgroundColor = UIColor.blackColor()
self.view.addSubview(self.PastObjectsCollection!)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1 //objectsCount
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Chow Object Reuse ID", forIndexPath: indexPath) as UICollectionViewCell
cell.backgroundColor = UIColor.whiteColor()
var imageView:UIImageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: 90, height: 90)
//imageView.image = imageThumbsArray[indexPath.row]
cell.addSubview(imageView)
return cell
}
}

Resources