Using CollectionView in UIView with xib file - ios

i'm doing with this, i want to use CollectionView, but i haven't seen prototype cell, and don't know how to use CollectionView in this case, can someone help me ?
I try to use like this way but it take alot of time and hard to manage than UICollectionView

The main way to use UICollectionView is by managing the logic programmatically.
First, create a new class which inherits from UICollectionViewCell. Choose if you want to include a xib to easily design your cell:
Design your cell with Interface Builder or programmatically.
Create your main view controller including a xib (or a storyboard) with the collection view inside and link it to the associated class via Interface Builder. Alternatively you can add a collection view programmatically to your UIViewController
Make the target view controller conform to the UICollectionViewDelegate and UICollectionViewDataSource protocols by declaring them after the father class:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
//...
}
Register the associated nib or the class for your cell in the viewDidLoad method and associate the datasource and delegate protocols to the view controller class:
let cellIdentifier = "cellIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
//if you use xibs:
self.collectionView.register(UINib(nibName:"MyCollectionCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier)
//or if you use class:
self.collectionView.register(MyCollectionCell.self, forCellWithReuseIdentifier: cellIdentifier)
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
Implement the methods declared in the UICollectionViewDelegate and UICollectionViewDataSource protocols :
let objects = ["Cat", "Dog", "Fish"]
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.objects.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! MyCollectionCell
//in this example I added a label named "title" into the MyCollectionCell class
cell.title.text = self.objects[indexPath.item]
return cell
}
Run your app in the simulator (or on a real device) and.. Et voilĂ ! :)
For more info: https://developer.apple.com/reference/uikit/uicollectionview

ok first you must have the IBOutlet of your collection view and implements the methods like this
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
#IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
count = 9;
let nib = UINib(nibName: "yourItemView", bundle: nil)
collectionView.registerNib(nib, forCellWithReuseIdentifier: "yourItemView")
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
ok in the function you add a xib file, next you must create that extend from UICollectionViewCell, and when you finish this you must override the next methods
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return count
// the numbers of items
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {//size of your item for screen sizes
let wsize = UIScreen.mainScreen().bounds.size.width
switch(wsize){
case 414:
return CGSize(width: 190, height: 102)
case 375:
return CGSize(width: 190, height: 102)
case 320:
return CGSize(width: 174, height: 102)
default:
return CGSize(width: 174, height: 102)
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("yourItemView", forIndexPath: indexPath) as! yourItemView
return cell
}
and this is all, good luck

Related

My super simple UICollectionView is not loading

I'm trying to create a simple collection view. I've got my custom cell "SectionCell" and the my custom class "Section", which contains two #IBOutlet properties: titleLabel and imageView. Both of these properties are hooked up to their respective storyboard views.
In storyboard, the collectionView scene has been linked to the MenuVC.swift file, which inherits from UICollectionView. The Cell view is linked to SectionCell. And I've set the cell's Identifier to "Section".
For debugging purposes I've set the view.backgroundColor to black and the cell's contentView background color to teal. Yet when I run the the simulator neither show. I get a white background and all that appears is the view title. Any ideas on what the fix is?
class MenuVC: UICollectionViewController {
var sections = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Begin Learning"
view.backgroundColor = .black
}
// MARK:- CollectionView Methods
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Section", for: indexPath) as? SectionCell else {
fatalError("Unable to dequeue SectionCell ")
}
let section = sections[indexPath.item]
cell.titleLabel.text = section.title
cell.imageView.image = UIImage(named: section.image)
return cell
}
}
class SectionCell: UICollectionViewCell {
#IBOutlet var imageView: UIImageView!
#IBOutlet var titleLabel: UILabel!
}
class Section: NSObject {
var title: String
var image: String
init(title: String, image: String) {
self.title = title
self.image = image
}
}
Simulator
I'm also quite new to posting questions on SO. If you have any tips on how to better format questions, I'm all ears!
make outlet of your collectionview and give it to the delegate and data source...
make outlet like this in your view controller:
#IBOutlet weak var collectionView: UICollectionview!
then put this code in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.relaodData()
}
have you implemented the following protocol?
UICollectionViewDelegateFlowLayout
extension MenuVC: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: 300.0, height: 300.0) // and set size for each item inside this function.
}
}
SOLVED
LOL you really do need eagle eyes as a developer. This:
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
is supposed to be:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
And voila!

Insert ViewControllers in UICollectionView calling lifeCycle methods - Swift - Programmatically

I'm using a UICollectionView to create a Swipeable Menu like this:
I've chosen to use a collectionView because it's so much easier than a PageViewController to perform some tasks (since UICollectionView is a subclass of UIScrollView).
There's one downside though, I don't know how to insert the ViewContollers inside the UICollectionViewcells and if upon scrolling the viewController's methods (such as ViewDidAppear, ViewDidDisappear) are called, I actually tried so many things but I couldn't find a way to solve this.
So summarising what I want to accomplish is: Insert ViewControllers inside CollectionViewCells so that when I scroll through the CollectionView, the lifecycle methods of VCs (ViewDidAppear, ViewDidDisappear) are called.
On StackOverFlow I've seen many topics talking about how to insert ViewControllers in cells but NEVER about calling the lifecycle methods inside them upon scrolling.
This is my CollectionView code:
private let reuseIdentifier1 = "Cell1"
private let reuseIdentifier2 = "Cell2"
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.isPagingEnabled = true
self.collectionView.bounces = false
self.collectionView!.register(CollectionViewCell1.self, forCellWithReuseIdentifier: reuseIdentifier1)
self.collectionView.register(CollectionViewCell2.self, forCellWithReuseIdentifier: reuseIdentifier2)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch indexPath.item {
case 0:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier1, for: indexPath)
return cell
default:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier2, for: indexPath)
return cell
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: view.frame.width, height: view.frame.height)
}}

Modifying the size of the cell of UICollectionView

I am trying to modify the size of the cells that the UICollectionview contains. I believe that the sizeForItemAtIndexPath should do the trick. Yet nothing is happening.
I have looked into similar questions, they have advised doing the same thing. I am sort of suspicious of my inheritance.
The problem is that the cells remain in the same size regardless of the value they were fed in.
class HikeViewController: UIViewController {
var test: Int?
#IBOutlet weak var options: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = false
print(test!)
options.dataSource = self
options.delegate = self
}
}
extension HikeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
//collectionCell
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
cell.backgroundColor = UIColor.green
return cell
}
func collectionView(collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath) -> CGSize
{
return CGSize(width: 400, height: 500)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath.row)
}
}
And when I conform to UICollectionViewDelegateFlowLayoutthe app termainates where I set the followings:
options.dataSource = self
options.delegate = self
And the error is:
Could not cast value of type 'HikingClub.HikeViewController' (0x108e1f948) to 'UICollectionViewDataSource' (0x10e723ff0).
It's worth adding that I have made sure of the connection between HikeViewController and the storyboard.
extension HikeViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
}
It should be something like this
Make your extension a subclass of UICollectionViewDelegateFlowLayout
Use the following function
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// code
}
You need to specify that you implement the protocol UICollectionViewDelegateFlowLayout in your class declaration.
extension HikeViewController: UICollectionViewDelegateFlowLayout {}
also you have are not calling the delegate method, just defining a new one.
check the first parameter (collectionView -> _ collectionView)
func collectionView(_ collectionView : UICollectionView,layout collectionViewLayout:UICollec

cellForItemAtIndexPath never called

I have a UICollectionView that I added to my UIViewController in my Storyboard.
It contains a UICollectionViewCell of class BookCell and reusable identifier BookCell.
bookArray gets passed in the prepareForSegue method from the previous ViewController
cellForItemAtIndexPath never gets called. I have attempted to declare BookCollectionVC as delegate and dataSource both in Storyboard and in viewDidLoad, as you can see commented out, but that does not change anything.
I have read multiple SO answers pertaining to cell size, to the number of items in the section, to the multiple ways of declaring delegate and dataSource and have tried/double checked all of them.
Any ideas?
class BookCollectionVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var collection: UICollectionView!
var bookArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// collection.delegate = self
// collection.dataSource = self
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("BookCell", forIndexPath: indexPath) as? BookCell {
// This never gets called
let bookIsbn = bookArray[indexPath.row]
cell.configureCell(bookIsbn)
return cell
} else {
return UICollectionViewCell()
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(bookArray.count)
return bookArray.count
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let cellWidth = screenWidth / 4
return CGSizeMake(cellWidth,cellWidth)
}
As a test, don't use an if-let. Just get the cell value and print it. What is its type? Have you properly assigned the cells to be the custom class (BookCell) in your StoryBoard?

UICollectionViewCell With Storyboard

I have a UICollectionView in Storyboard, in a UICollectionViewController. The UICollectionViewController is linked to my custom class MasterViewController: UICollectionViewController, UICollectionViewDataSource, UICollectionViewDelegate, and it's delegate and datasource are linked in the storyboard to this class.
I have a prototype UICollectionViewCell in storyboard, with an identifier "MyCell", from my custom class Cell: UICollectionViewCell
In the cellForItemAtIndexPath method, the app crash at the line : let cell:Cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as Cell
I don't find why. I haven't implemented the registerClass:forCellWithReuseIdentifier: method, and the identifier of the storyboard is exactly "MyCell", I checked many times, and the delegate and datasource are linked to the right class.
When the app crash, nothing is printed in the console, just "(lldb)"
Here's my code :
class MasterViewController: UICollectionViewController,UICollectionViewDataSource,UICollectionViewDelegate {
var objects = [ObjectsEntry]()
#IBOutlet var flowLayout: UICollectionViewFlowLayout!
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
flowLayout.itemSize = CGSizeMake(collectionView!.bounds.width - 52, 151)
}
// MARK: - Collection View
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return objects.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:Cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as Cell
return cell
}
I had the same problem. Raywenderlich Swift manual helped me. I copying MyCollectionViewController here.
Identifier must match in controller and Storyboard.
Create custom UICollectionViewCell class.
Set this UICollectionViewCell in Storyboard.
Do not call viewDidLoad().
Do not call registerClass:forCellWithReuseIdentifier:
Set cell item size with UICollectionViewDelegateFlowLayout in collectionView:layout:sizeForItemAtIndexPath:.
import UIKit
class MyCollectionViewController:
UICollectionViewController,
UICollectionViewDelegateFlowLayout {
private let reuseIdentifier = "ApplesCell"
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as MyCollectionViewCell
cell.backgroundColor = UIColor.redColor()
cell.imageView.image = UIImage(named: "red_apple")
return cell
}

Resources