Swift - Change UICollectionViewCell size programmatically - ios

I am struggling to change the size my items in the CollectionView.
Custom Flowlayout class found here:
This is my CollectionView:
class ExampleViewController: UIViewController, UICollectionViewDataSource {
let theCollectionView: UICollectionView = {
let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .white
v.contentInsetAdjustmentBehavior = .always
v.layer.cornerRadius = 30
return v
}()
let columnLayout = FlowLayout(
itemSize: CGSize(width: 50, height: 50),
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: UIEdgeInsets(top: 20, left: 20, bottom: 10, right: 20)
)
I tried changing the itemSize but that doesnt do anything.

You didn't assigned you flowLayout to the collectionView either try:
theCollectionView.collectionViewLayout = columnLayout or
First define your layout :
let columnLayout = FlowLayout( ...
Then define your collectionView like this:
let theCollectionView: UICollectionView = {
let v = UICollectionView(frame: CGRect.zero, collectionViewLayout:columnLayout)

Here is Code for CollectionViewCell Size Change
(Note:- Change values according to your Requirement!)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth/4, height: screenWidth/4)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
cell2.collectionView2.collectionViewLayout = layout

Related

errors with UICollectionViewFlowLayout scrolling

I am setting up a UiCollectionView and I am trying to have the view scroll horizontally. The View is setup up and I can see labels and images but it does not scroll at all. The height of the collectionViewCell itself is 350 and how i am setting up the cell is
let SubView: UIView = {
let view = UIView()
view.backgroundColor = GREEN_Theme
view.layer.cornerRadius = 10
return view
}()
let headerLabel: UILabel = {
let label = UILabel()
label.text = "label"
label.font = UIFont.systemFont(ofSize: 30)
label.font = .boldSystemFont(ofSize: 30)
label.numberOfLines = 0
label.textColor = UIColor.black
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
addSubview(SubView)
SubView.anchors(top: topAnchor, topPad: 0, bottom: nil, bottomPad: 0, left: leftAnchor, leftPad: 0, right: rightAnchor, rightPad: 0, height: 1, width: self.bounds.width - 20)
addSubview(headerLabel)
headerLabel.anchors(top: SubView.bottomAnchor, topPad: 5 , bottom: nil, bottomPad: 0, left: safeAreaLayoutGuide.leftAnchor, leftPad: 15, right: nil, rightPad: 0, height: 50, width: 200)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let recentCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.clear
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
func setupViews() {
backgroundColor = UIColor.clear
addSubview(recentCollectionView)
contentView.isUserInteractionEnabled = true
recentCollectionView.dataSource = self
recentCollectionView.delegate = self
recentCollectionView.isUserInteractionEnabled = true
recentCollectionView.backgroundColor = UIColor.blue
recentCollectionView.register(recentCell.self, forCellWithReuseIdentifier: cellID)
recentCollectionView.layer.zPosition = 1
recentCollectionView.topAnchor.constraint(equalTo: topAnchor, constant: 40).isActive = true
recentCollectionView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 5).isActive = true
recentCollectionView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5).isActive = true
recentCollectionView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -40).isActive = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return reviews.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! recentCell
cell.configureCell(reviews[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: frame.height - 5)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 100, left: 14, bottom: 0, right: 14)
}
}
class recentCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
let imageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "rake")
iv.contentMode = .scaleAspectFill
iv.layer.cornerRadius = 16
iv.layer.masksToBounds = true
return iv
}()
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Zach Wilcox"
label.font = UIFont.systemFont(ofSize: 14)
label.numberOfLines = 2
return label
}()
let categoryLabel: UILabel = {
let label = UILabel()
label.text = "Yard Work"
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = UIColor.darkGray
return label
}()
let starControls = starStackView()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews() {
addSubview(imageView)
addSubview(nameLabel)
addSubview(categoryLabel)
addSubview(starControls)
starControls.translatesAutoresizingMaskIntoConstraints = false
starControls.distribution = .fillEqually
imageView.frame = CGRect(x:0, y: 0, width: frame.width, height: frame.width)
nameLabel.anchors(top: imageView.bottomAnchor, topPad: 1, bottom: nil, bottomPad: 0, left: imageView.leftAnchor, leftPad: 0, right: nil, rightPad: 0, height: 20, width: 100)
categoryLabel.anchors(top: nameLabel.bottomAnchor, topPad: 1, bottom: nil, bottomPad: 0, left: imageView.leftAnchor, leftPad: 0, right: nil, rightPad: 0, height: 20, width: 100)
starControls.anchors(top: categoryLabel.bottomAnchor, topPad: 1, bottom: nil, bottomPad: 0, left: imageView.leftAnchor, leftPad: 0, right: nil, rightPad: 0, height: 20, width: 100)
}
In my console, I see
the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.
I have tried to set the background colors to blue in the recentCollectionView and the collectionView itself to see if the if the height of the cell is exceeding the height of the collectionView but it is not.
images below,
the first image, is the size of the entire contentView.
and this image is the size of the recentCollectionView
as we can see with the images, the recentCollectionView is not larger than the collectionView. Why am I seeing this error and why will my collectionViewFlowLayout not scroll?
I have found an answer shortly after posting my question but did not want to delete just in case some other newbie had the same problem. All I had to do was add the recentCollectionView to the contentView's subview not simply just addSubview.
contentView.addSubview(recentCollectionView)
super simple fix.

CollectionView does not scroll when added to view

Here is my code:
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = .greatestFiniteMagnitude
layout.minimumLineSpacing = 15
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: screenWidth*0.2, height: screenHeight*0.15)
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenWidth*0.9, height: screenHeight*0.15), collectionViewLayout: layout)
collectionView?.layer.zPosition = 10
collectionView?.register(PlantSnapshotCell.self,forCellWithReuseIdentifier:PlantSnapshotCell.identifier)
collectionView?.backgroundColor = .clear
collectionView?.alwaysBounceHorizontal = true
collectionView?.bounces = true
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.dataSource = self
collectionView?.delegate = self
scrollView.addSubview(collectionView!)
view.addSubview(scrollView)
It renders in the view, but any sort of interaction does not work. The width of the collectionView is 90% the width of the superview. Scrolling horizontally does not work.
Why you are adding collectionView as a subview to the scrollView?

UICollectionCell position issue

CollectionView cell is not coming at correct position. I am using following code to create the Collection view
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
viewListCollection = UICollectionView(frame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), collectionViewLayout: layout)
layout.headerReferenceSize = CGSizeZero
layout.footerReferenceSize = CGSizeZero
viewListCollection.dataSource = self
viewListCollection.delegate = self
viewListCollection.backgroundColor = UIColor.whiteColor()
viewListCollection.tag = 9999
viewListCollection.registerNib(UINib(nibName: "SelectedContactCell", bundle: nil), forCellWithReuseIdentifier: "SelectedContactCell")
viewListCollection.scrollEnabled = true
viewListCollection.collectionViewLayout = layout
self.addSubview(viewListCollection)
blue colour is of CollectionView and yellow colour is of CollectionViewCell . You can see the top distance of the cell, why this space is coming.And how to remove that?
Try this in your viewDidLoad:
self.automaticallyAdjustsScrollViewInsets = false

UICollectionView Magic Selection

I added collection view and add selection events:
private func addFriendCollectionView() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let cellSize = (mainContainerView?.frame.width)! / 4
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 50, right: 10)
layout.itemSize = CGSize(width: cellSize, height: cellSize)
layout.minimumLineSpacing = 50.00
let positionRectangle = CGRect(x: 5, y: 230, width: (mainContainerView?.frame.width)!, height: 300)
friendsCollection = UICollectionView(frame: positionRectangle, collectionViewLayout: layout)
friendsCollection?.registerClass(FriendCollectionViewCell.self, forCellWithReuseIdentifier: "friendCell")
friendsCollection?.backgroundColor = UIColor.whiteColor()
friendsCollection!.layer.borderColor = UIColor.grayColor().CGColor
friendsCollection!.layer.borderWidth = 0.5
friendsCollection?.tag = 1
friendsCollection?.allowsMultipleSelection = true
friendsCollection?.dataSource = self
friendsCollection?.delegate = self
self.view.addSubview(friendsCollection!)
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if collectionView.tag == 1 {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! FriendCollectionViewCell
selectedFriends[indexPath] = cell.friendName.text
cell.selectBlackView.hidden = false
cell.selectedImage.hidden = false
print("\(selectedFriends.count) - \(indexPath)")
} else if collectionView.tag == 2 {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! DateSelectionCollectionViewCell
print("\(cell.weekday.text) and \(indexPath)")
}
}
But selection layer add every cell with offset 9. If i am select 1 selected 10, 19, 28... etc but indexPath change correct

Block row and column CollectionView scroll

And this is my code :
var collectionView: UICollectionView?
var collectionViewSeries: UICollectionView?
override func viewDidLoad() {
super.viewDidLoad()
// Year
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 90, height: 120)
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
collectionView!.backgroundColor = UIColor.whiteColor()
collectionView?.scrollEnabled = false
self.view.addSubview(collectionView!)
// Series
let layoutSeries: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layoutSeries.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layoutSeries.itemSize = CGSize(width: 90, height: 120)
layoutSeries.scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionViewSeries = UICollectionView(frame: self.view.frame, collectionViewLayout: layoutSeries)
collectionViewSeries!.dataSource = self
collectionViewSeries!.delegate = self
collectionViewSeries!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellSeries")
collectionViewSeries!.backgroundColor = UIColor.whiteColor()
collectionViewSeries?.scrollEnabled = true
self.view.addSubview(collectionViewSeries!)
}
My question:
I'm trying to block the first column and the first row by scrolling.
So that only the central cells can flow.
This is an example of what I want to do:
link
Thanks
scrolling cannot be disabled for a particular cell. You create a UIView in Section Header similar to Cell 1. This will work as you like.
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] init]; //your view
return view;
}

Resources