I have a collection view that scrolls horizontally, but I cannot figure out how to make the cells center and stop at the center of each scroll. So for example if you swift left the next cell should be centered in the middle of the screen, how can I do this? I'll post the collection view I have created:
class TakesViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
private lazy var selectionFeedbackGenerator = UISelectionFeedbackGenerator()
private let cellId = "TakeCell"
var currentActiveIndex: Int = 0
func setUpCollectionView(){
self.collectionView.isPrefetchingEnabled = true
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
self.collectionView.backgroundColor = .clear
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.showsVerticalScrollIndicator = false
self.collectionView.contentInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
self.collectionView.alwaysBounceVertical = false
self.collectionView.alwaysBounceHorizontal = false
self.collectionView.decelerationRate = .fast
self.collectionView.configureForPeekingDelegate()
self.collectionView.register(UINib(nibName: "TakesCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "TakeCell")
}
init() {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 15
super.init(collectionViewLayout: flowLayout)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
setUpCollectionView()
}
}
extension TakesViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as? TakeCollectionViewCell else {return UICollectionViewCell()}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 320, height: 575)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//Where elements_count is the count of all your items in that
//Collection view...
let cellCount = CGFloat(12)
//If the cell count is zero, there is no point in calculating anything.
if cellCount > 0 {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing
//20.00 was just extra spacing I wanted to add to my cell.
let totalCellWidth = cellWidth*cellCount + 20.00 * (cellCount-1)
let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right
if (totalCellWidth < contentWidth) {
//If the number of cells that exists take up less room than the
//collection view width... then there is an actual point to centering them.
//Calculate the right amount of padding to center the cells.
let padding = (contentWidth - totalCellWidth) / 2.0
return UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
} else {
//Pretty much if the number of cells that exist take up
//more room than the actual collectionView width, there is no
// point in trying to center them. So we leave the default behavior.
return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
}
}
return UIEdgeInsets.zero
}
}
It's a scroll view. Where it stops when the user lets go is up to you.
https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619385-scrollviewwillenddragging
Related
I have a UIcollectionview that allows scrolling the content horizontally only. Each UIcollectionviewCell is a custom view showing two labels one below the other. I have set constraints in the custom cell to position these labels. Irrespective of the screen width, I always want to show 7 UICollection cells. Is this possible?
You need to change itemSize by calculating from device width
let itemSpacing: CGFloat = 5
let itemsInOneLine: CGFloat = 7
let flow = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flow.sectionInset = UIEdgeInsets(top: itemSpacing, left: itemSpacing, bottom: itemSpacing, right: itemSpacing)
flow.minimumInteritemSpacing = itemSpacing
flow.minimumLineSpacing = itemSpacing
let cellWidth = (UIScreen.main.bounds.width - (itemSpacing * 2) - ((itemsInOneLine - 1) * itemSpacing)) / itemsInOneLine
flow.itemSize = CGSize(width: cellWidth, height: 120)
Hope this is What you want,
Here is the code for this.
//
// ViewController.swift
// AssignmentSO
//
// Created by Anuradh Caldera on 4/24/19.
// Copyright © 2019 personal. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private var mycollectionview: UICollectionView!
private let cellidentifier = "cellIdentifier"
private let minimuminterspace: CGFloat = 2
override func viewDidLoad() {
super.viewDidLoad()
setCollectionView()
}
}
extension ViewController {
fileprivate func setCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = minimuminterspace
layout.minimumInteritemSpacing = minimuminterspace
mycollectionview = UICollectionView(frame: .zero, collectionViewLayout: layout)
mycollectionview.translatesAutoresizingMaskIntoConstraints = false
mycollectionview.register(MyCell.self, forCellWithReuseIdentifier: cellidentifier)
mycollectionview.dataSource = self
mycollectionview.delegate = self
mycollectionview.backgroundColor = .white
mycollectionview.isPagingEnabled = true
// mycollectionview.contentInset = UIEdgeInsets(top: 0, left: minimuminterspace, bottom: 0, right: minimuminterspace)
view.addSubview(mycollectionview)
let collectionviewConstraints = [mycollectionview.leftAnchor.constraint(equalTo: view.leftAnchor, constant: minimuminterspace),
mycollectionview.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
mycollectionview.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -minimuminterspace),
mycollectionview.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height/4)]
NSLayoutConstraint.activate(collectionviewConstraints)
}
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellidentifier, for: indexPath) as! MyCell
cell.index = indexPath.item
cell.backgroundColor = .purple
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellwidth = mycollectionview.frame.width/7 - minimuminterspace
let cellheight = mycollectionview.frame.height
return CGSize(width: cellwidth, height: cellheight)
}
}
class MyCell: UICollectionViewCell {
private var mainlabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
setLabel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var index: Int! {
didSet {
mainlabel.text = "\(index+1)"
}
}
}
extension MyCell {
fileprivate func setLabel() {
mainlabel = UILabel()
mainlabel.translatesAutoresizingMaskIntoConstraints = false
mainlabel.textColor = .white
mainlabel.textAlignment = .center
addSubview(mainlabel)
let mainlabelConstraints = [mainlabel.centerXAnchor.constraint(equalTo: centerXAnchor),
mainlabel.centerYAnchor.constraint(equalTo: centerYAnchor)]
NSLayoutConstraint.activate(mainlabelConstraints)
}
}
Note: if you want to show 7 cells, then it is better to enable pagination. you can change the height as your need. hope this will help to someone. cheers!
Step 1 - Implement UICollectionViewDelegateFlowLayout delegate
Step 2 - Add below method
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (collectionViewSize/7) , height: 50 )
}
Step 3 - pass size according to your requirement
Implement the collectionView layout delegate.
And divide the screen width in 7 parts as below.
please note following code is with respect to the collectionView width, considering the auto layout of collectionView width is set to screen margin.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width/7, height:collectionView.bounds.height)
}
Though this will suffice your need, you will also need to handle the Cell's subviews to fit in the cell and display the content properly.
I have a UICollectionView that I have implemented to scroll horizontally but for some reason when I scroll through there are only 3 cells that are presented (when there should be 9)
class BusinessPhotosViewController: UICollectionViewController ,UICollectionViewDelegateFlowLayout{
let cellId = "photos"
override func viewDidLoad() {
super.viewDidLoad()
if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
}
collectionView?.register(BusinessPhotoCells.self, forCellWithReuseIdentifier: cellId)
collectionView?.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
collectionView?.scrollIndicatorInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
collectionView?.isPagingEnabled = true
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 9
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BusinessPhotoCells
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = view.frame.width / 3
return CGSize(width: width, height: width)
}
}
I present this BusinessPhotosViewController within the cell of ANOTHER UICollectionViewController called BusinessDetailViewController
class BusinessDetailViewController : UICollectionViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let scrollCell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureCellId, for: indexPath)
let bizVC = BusinessPhotosViewController(collectionViewLayout: UICollectionViewFlowLayout())
scrollCell.addSubview(bizVC.view)
bizVC.view.anchor(top: scrollCell.topAnchor, left: scrollCell.leftAnchor, bottom: scrollCell.bottomAnchor, right: scrollCell.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: scrollCell.frame.width, height: scrollCell.frame.height)
return scrollCell
}
}
So I can see that the scrolling works, but the issue I'm seeing is that only 3 cells are loaded (out of 9) and the view looks something like this:
I've seen these solutions here and here and other but none helped me.
I tried your code and I can see all the 9 cells if the size of 9 cell is smaller than the size scroll cell size.
import UIKit
class ViewController: UIViewController{
override func viewDidLoad() {
view.backgroundColor = .red;
view.addSubview(photosContainer);
photosContainer.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true;
photosContainer.topAnchor.constraint(equalTo: view.centerYAnchor).isActive = true;
photosContainer.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true;
photosContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.4).isActive = true;
***let layout = UICollectionViewFlowLayout();
layout.scrollDirection = .horizontal
let bizVC = BusinessPhotosViewController(collectionViewLayout: layout)
bizVC.view.frame = photosContainer.bounds;
photosContainer.addSubview(bizVC.view)***
}
let photosContainer : UIView = {
let view = UIView();
view.backgroundColor = .green;
view.translatesAutoresizingMaskIntoConstraints = false;
return view;
}();
}
Before adding the view if you set the frame then I can see all the nine cells no matter their size.
Let me know if it works
To show only two columns in a collectionView i am using this piece of code
let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.minimumInteritemSpacing = 4
layout.itemSize = CGSize(width:(self.collectionView.frame.size.width - 10)/2,height: (self.collectionView.frame.size.height)/3)
but it is only showing properly on 5s, not on every iphone. please help.
i want to show my view controller like this image. please help anyone
You must be missing UICollectionViewDelegateFlowLayout
Try this and see:
// Source code
import UIKit
class CollectionVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
#IBOutlet var collection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collection.delegate = self
collection.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//collection.reloadData()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let flowayout = collectionViewLayout as? UICollectionViewFlowLayout
let space: CGFloat = (flowayout?.minimumInteritemSpacing ?? 0.0) + (flowayout?.sectionInset.left ?? 0.0) + (flowayout?.sectionInset.right ?? 0.0)
let size:CGFloat = (collection.frame.size.width - space) / 2.0
return CGSize(width: size, height: size)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 50
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "testcell", for: indexPath)
cell.backgroundColor = UIColor.red
return cell
}
}
// Interface Design
Result:
Make sure your protocol confirms to your ViewController,
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
And set flow layout to your collectionview object
In viewDidLoad
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical //.horizontal
layout.minimumLineSpacing = 5
layout.minimumInteritemSpacing = 5
collectionView.setCollectionViewLayout(layout, animated: true)
And implement following methods
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 1.0, left: 1.0, bottom: 1.0, right: 1.0)//here your custom value for spacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let lay = collectionViewLayout as! UICollectionViewFlowLayout
let widthPerItem = collectionView.frame.width / 2 - lay.minimumInteritemSpacing
return CGSize(width:widthPerItem, height:100)
}
add this code to viewDidLoad.
change height according to you.
try this!
if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout{
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
let size = CGSize(width:(collectionView!.bounds.width-30)/2, height: 250)
layout.itemSize = size
}
Update for Swift 5 and XCode 12.4
import UIKit
class TwoColumnViewController: UIViewController {
enum Section {
case main
}
var dataSource: UICollectionViewDiffableDataSource<Section, Int>! = nil
var collectionView: UICollectionView! = nil
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Two-Column Grid"
configureHierarchy()
configureDataSource()
}
}
extension TwoColumnViewController {
/// - Tag: TwoColumn
func createLayout() -> UICollectionViewLayout {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(44))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 2)
let spacing = CGFloat(10)
group.interItemSpacing = .fixed(spacing)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = spacing
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
}
extension TwoColumnViewController {
func configureHierarchy() {
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.backgroundColor = .systemBackground
view.addSubview(collectionView)
}
func configureDataSource() {
let cellRegistration = UICollectionView.CellRegistration<TextCell, Int> { (cell, indexPath, identifier) in
// Populate the cell with our item description.
cell.label.text = "\(identifier)"
cell.contentView.backgroundColor = .cornflowerBlue
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.label.textAlignment = .center
cell.label.font = UIFont.preferredFont(forTextStyle: .title1)
}
dataSource = UICollectionViewDiffableDataSource<Section, Int>(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, identifier: Int) -> UICollectionViewCell? in
// Return the cell.
return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: identifier)
}
// initial data
var snapshot = NSDiffableDataSourceSnapshot<Section, Int>()
snapshot.appendSections([.main])
snapshot.appendItems(Array(0..<94))
dataSource.apply(snapshot, animatingDifferences: false)
}
}
I have following code which I have implemented to display two column in collection view.
Add UICollectionViewDelegateFlowLayout’s following method method:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = (collectionView.frame.size.width - 30) / 2
return CGSize(width: size, height: size)
}
Where 30 stand for left, right and middle space between cell.
i.e Cell should be add 10 pixel on left Side, 10 pixel on right side and 10 pixel in between two cell.
Select you collectionview from storyboard and from Size Inspector set following minimum spacing.
I hope this will fix you issue.
Let me know if any query.
I'm facing strange issue. My UICollectionView display half side colums if I scrolling to down.
At first they show perfectly like this
But when I scrolling down, the UICollectionView behave strange and look like this :
Below is my code to populate data to layout (dummy) :
let layoutProduct: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layoutProduct.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layoutProduct.scrollDirection = .vertical
collectionViewProduk = UICollectionView(frame: self.view.frame, collectionViewLayout: layoutProduct)
collectionViewProduk.dataSource = self
collectionViewProduk.delegate = self
collectionViewProduk.register(ProdukPopulerCell.self, forCellWithReuseIdentifier: "ProductCell")
collectionViewProduk.backgroundColor = UIColor(red: 231/255.0, green: 231/255.0, blue: 231/255.0, alpha: 1.0)
self.view.addSubview(collectionViewProduk)
How many data to show :
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionViewByFilter {
return 4
} else if collectionView == self.collectionViewProduk {
return 8
}
return section
}
How I populate dummy data to cell :
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionViewProduk {
if let cellA = collectionViewProduk.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) as? ProdukPopulerCell {
cellB.backgroundColor = UIColor.white
if indexPath.row < 8 {
cellB.nameLabel.text = "Product"
cellB.theImageView.image = UIImage(named: "biometric")
cellB.priceLabel.text = "Rp 30.000"
}
return cellB
}
}
return UICollectionViewCell()
}
How I layouting the cell and make them look 2 cell in 1 rows :
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView == self.collectionViewProduk {
let collectionViewSize = collectionViewProduk.frame.size.width - 10
return CGSize(width: collectionViewSize / 2, height: collectionViewSize / 2)
}
return CGSize()
}
Can you guys spot the mistake that I make?
Create a customCollectionViewFlowLayout and apply it to your collectionview
import UIKit
class customCollectionViewFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayout()
}
func setupLayout() {
minimumInteritemSpacing = 1
minimumLineSpacing = 1
scrollDirection = .vertical
}
override var itemSize: CGSize {
set {
}
get {
let numberOfColumns: CGFloat = 2
let itemWidth = (self.collectionView!.frame.width - (numberOfColumns - 1)) / numberOfColumns
return CGSize(width:itemWidth, height:itemWidth)
}
}
}
then apply it to your collectionview
yourCollectionView.collectionViewLayout = customCollectionViewFlowLayout()
I Wanted to design the UICollectionview both portrait and landscape mode.Here i am using UICollectionViewFlowLayout
I have entered my view controller code
import UIKit
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
#IBOutlet var collectionObject: UICollectionView!
var isOrientation = true
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
layout.itemSize = CGSize(width: 90, height: 90)
layout.scrollDirection = .horizontal
collectionObject.collectionViewLayout = layout
collectionObject!.register(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
NotificationCenter.default.addObserver(self, selector: #selector(self.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
collectionObject.delegate = self
collectionObject.dataSource = self
self .adjustContentInsets()
}
func rotated() {
if UIDevice.current.orientation.isLandscape {
print("Landscape")
// layout.scrollDirection = .vertical
isOrientation = false
} else {
print("Portrait")
//layout.scrollDirection = .horizontal
isOrientation = true
}
collectionObject?.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UICOLLECTIONVIEW DELEGATES AND DATASOURCE
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.orange
cell.textLabel.text = String(indexPath.item)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var width :CGFloat = 0
var height :CGFloat = 0
if isOrientation == true {
width = self.collectionObject!.frame.size.width / 2
height = self.collectionObject!.frame.size.height / 2
}else{
width = self.collectionObject!.frame.size.height / 2
height = self.collectionObject!.frame.size.height / 2
}
if indexPath.row == 0 {
return CGSize(width: width, height: height)
}else if(indexPath.row == 1 || indexPath.row == 2){
return CGSize(width: width / 2, height: height / 2)
}else{
var isLwidth :CGFloat = 0
if isOrientation == true {
isLwidth = self.collectionObject!.frame.size.width / 2 - 40
}else{
isLwidth = self.collectionObject!.frame.size.width / 2 - 3
}
return CGSize(width: isLwidth, height: 100)
}
//return CGSize(width: self.view.frame.size.width-200, height: self.view.frame.size.height-250)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}
func adjustContentInsets() {
let inset = UIEdgeInsetsMake(UIApplication.shared.statusBarFrame.size.height, 0, 0, 0)
self.collectionObject.contentInset = inset
self.collectionObject.scrollIndicatorInsets = inset
}
}
My output not coming as excepted:
Portrait Mode
Landscape Mode
The output is entire wrong, i am doing wrong with sizeForItemAt delegate.How to make layout like below using UICollectionview?
Actual Design:
Portrait
Landscape
Here The collection view should not scroll both direction.The array count always 10 only.
I wanted to fit CollectionViewCell with in view Bounds
The bottom blue colour view is different UIView.
Or Is there any possible way to achieve this by single control?
Thanks in advance!!!