Consider the following situation. I have an UICollectionView (inside UICollectionViewController), which looks almost the same as UITableView (the reason why I don't use UITalbeView is because I have non data views on layout, that I don't want to manage and mess with my IndexPath).
In order to achieve the autosizing cells I've set estimatedItemSize, something like that:
layout.estimatedItemSize = CGSize(width: self.view.bounds.size.width, height: 72)
Also, in my cell I have layout attributes:
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
return layoutAttributes
}
So, by doing that I've got exact layout as UITableView with autosizing. And it works perfectly.
Now, I am trying to add the header and pin it on scrolling to the top of the section, like that:
layout.sectionHeadersPinToVisibleBounds = false
but layout goes into weird state, I have glitches all over the place, cells overlapping each other, and headers sometimes doesn't stick.
UPDATE:
The code of view controller and cell:
class ViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionHeadersPinToVisibleBounds = true
layout.estimatedItemSize = CGSize(width: collectionView?.bounds.size.width ?? 0, height: 36) // enables dynamic height
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 10
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
cell.heightConstraint.constant = CGFloat(indexPath.row * 10 % 100) + 10 // Random constraint to make dynamic height work
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath)
}
class CustomCell : UICollectionViewCell {
let identifier = "CustomCell"
#IBOutlet weak var rectangle: UIView!
#IBOutlet weak var heightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
translatesAutoresizingMaskIntoConstraints = false
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
return layoutAttributes
}
Details of lagging in video: https://vimeo.com/203284395
Update from WWDC 2017:
My colleague was on WWDC 2017, and he asked one of the UIKit engineers about this issue. The engineer confirmed that this issue is known bug by Apple and there is no fix at that moment.
Use the UICollectionViewDelegateFlowLayout method.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
//Calculate your Dynamic Size Here for Each Cell at SpecificIndexPath.
//For Example You want your Cell Height to be dynamic with Respect to indexPath.row number
let cellWidth = collectionView?.bounds.size.width
//Now Simply return these CellWidth and Height, and you are Good to go.
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCellIdentifier", for: indexPath)
//You Can Pass TextField As Well as i have considered UITextView for now.
let cellSize = self. calculateSize(cellTextView: cell.textView, cellText: yourArrayOfText[indexPath.row], withFixedWidth: cellWidth)
return cellSize
}
And do not change the Cell Height by changing the Constraint.constant directly. Instead of this simply use Above Delegate method to change height. Changing Cell Constraint can cause issues like this.
Use bellow method to get your desired Size.
func calculateSize(cellTextView: UITextView, cellText: String, withFixedWidth: CGFloat) -> CGSize {
let textView = UITextView()
textView.text = cellText
textView.frame = cellTextView.frame
textView.font = cellTextView.font
textView.tag = cellTextView.tag
let fixedWidth = withFixedWidth
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
return newSize
}
Use Bellow method to calculate the image size.
//Method to Calculate ImageSize.
func calculateImageSize(image: UIImage) -> CGSize {
var newSize = image.size
if newSize.width > (ChatView.maxWidth - 70) {
newSize.width = ChatView.maxWidth - 70
newSize.height = ChatView.maxWidth - 70
}
if newSize.height < 60 {
newSize.height = 60
newSize.width = 60
}
return newSize
}
Related
I need to create a vertical CollectionView which have a dynamic label and all CollectionViewCell height should be same to the largest cell content. How to calculate largest cell height and assign that height to every cell?
I have tried many solution but none is working for me.
Any solution pls
Thanks in advance.
Start by adding the following UILabel Extension (add anywhere outside of the ViewController):
extension UILabel{
public var getHeight: CGFloat {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.attributedText = attributedText
label.sizeToFit()
return label.frame.height
}
}
Then you can calculate the height for each label while the collection view cell is rendering. In the following, I check to see if the new height is greater then the last tallest height - this is saved to my variable called tallestCellHeight. Use this variable to set the height of the cell.
var tallestCellHeight: CGFloat = 0
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "testCell", for: indexPath) as! testCell
cell.testLabel.text = messages[indexPath.row]
let currentCellHeight = cell.testLabel.getHeight
if currentCellHeight > tallestCellHeight {
tallestCellHeight = currentCellHeight
print(tallestCellHeight)
}
cell.backgroundColor = .tertiarySystemFill
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
CGSize(width: 150, height: tallestCellHeight)
}
After the collection view has rendered, I will have the tallest cell height saved to the variable tallestCellHeight.
Lastly, reload the collection view on the main thread in viewDidLoad()
DispatchQueue.main.async {
self.collectionView.reloadData()
}
Don't forget to include UICollectionViewDelegate, UICollectionViewDataSource and UICollectionViewDelegateFlowLayout
Entire Code
import UIKit
let messages: [String] = ["hello and welcome", "this is a really cool app", "this is awesome", "welcome to the test for my new application", "hello everyone"]
class testCell: UICollectionViewCell {
#IBOutlet weak var testLabel: UILabel!
}
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
var tallestCellHeight: CGFloat = 0
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "testCell", for: indexPath) as! testCell
cell.testLabel.text = messages[indexPath.row]
let currentCellHeight = cell.testLabel.getHeight
if currentCellHeight > tallestCellHeight {
tallestCellHeight = currentCellHeight
print(tallestCellHeight)
}
cell.backgroundColor = .tertiarySystemFill
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
CGSize(width: 150, height: tallestCellHeight)
}
}
extension UILabel{
public var getHeight: CGFloat {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.attributedText = attributedText
label.sizeToFit()
return label.frame.height
}
}
I am trying to dynamically set the width of collection view cell. Initially it's not rendering as expected. But when I tap on the cell, its getting adjusted as I want. Here's the code that I wrote:
Code
import UIKit
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
#IBOutlet weak var collView: UICollectionView!
var tasksArray = ["To Do", "SHOPPING","WORK"]
var selectedIndex = Int()
override func viewDidLoad() {
super.viewDidLoad()
let layout = collView?.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = UICollectionViewFlowLayout.automaticSize
layout.estimatedItemSize = CGSize(width: 93, height: 40)
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tasksArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.lblName.text = tasksArray[indexPath.row]
if selectedIndex == indexPath.row
{
cell.backgroundColor = UIColor.lightGray
}
else
{
cell.backgroundColor = UIColor.white
}
cell.layer.borderWidth = 1
cell.layer.cornerRadius = cell.frame.height / 2
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndex = indexPath.row
self.collView.reloadData()
}
}
here i am attaching two image before tapping and after tapping so you can easily understood
[![Here is the image before i tap
on cell]2]2
so please tell me whats wrong in my code
Inside your CollectionViewCell override preferredLayoutAttributesFitting function This is where the cell has a chance to indicate its preferred attributes, including size, which we calculate using auto layout.
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var frame = layoutAttributes.frame
frame.size.width = ceil(size.width)
layoutAttributes.frame = frame
return layoutAttributes
}
I have found a small trick for swift 4.2
For dynamic width & fixed height:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let label = UILabel(frame: CGRect.zero)
label.text = textArray[indexPath.item]
label.sizeToFit()
return CGSize(width: label.frame.width, height: 32)
}
It is obvious that you have to use sizeForItemAt flow layout delegate in order to pass the dynamic width. But the tricky part is to calculate the width of the cell based on the text. You can actually calculate the width of a text given that you have a font.
Let's introduce few extension which will help us along the way
StringExtensions.swift
extension String {
public func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect,
options: .usesLineFragmentOrigin,
attributes: [.font: font], context: nil)
return ceil(boundingBox.width)
}
}
This method let us know the width of a string, if i provide it the height and the font. Then use it inside sizeForItem as follows
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = 40
let text = YOUR_TEXT
let width = text.width(withConstrainedHeight: height, font: Font.regular.withSize(.extraSmall)) + EXTRA_SPACES_FOR_LEFT_RIGHT_PADDING
return CGSize(width: width, height: height)
}
Question:
How To Make UITableViewCell Height Dynamic according the UICollectionViewCell?
View Hierarchy:
UIViewController
UITableView
UITableViewCell
UICollectionView
UICollectionViewCell1
Label 1
UICollectionViewCell2
Label 2
UICollectionViewCell3
Label 3
[So on]
Explanation:
Here Label1, Label2, label 3 are have dynamic height and numberOfRows in UICollectionView is also dynamic. I need Height of UITableViewCell according to the UICollectionViewCell.
View Hierarchy In UIViewController
Steps:
Bind Delegate And Datasource
Bind UITableView delegate and datasource with the UIViewController.
Bind UICollectionView Delegate and datasource with the UITableViewCell here TblCell.
In UIViewController
class CollectionVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
:
:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension // For tableCell Dynamic Height
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 200 // For tableCell Estimated Height
}
// Above two delegates must be necessary or you can use property for same.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1 // returning 1, as per current single cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TblCell") as! TblCell
return cell
}
}
In TblCell
class TblCell: UITableViewCell , UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
#IBOutlet var colViewObj: UICollectionView!
// Array for Label
var arrData = ["Hello", "How re you?", "rock the world", "Nice to meet you.", "Hey! It is awsome."]
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.colViewObj.isScrollEnabled = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// Get width of Label As per String characters.
let aWidth : CGFloat = arrData[indexPath.row].width(withConstraintedHeight: 40, font: UIFont.systemFont(ofSize: 17.0))
return CGSize(width: aWidth + 40 , height: 40)
}
// THIS IS THE MOST IMPORTANT METHOD
//
// This method tells the auto layout
// You cannot calculate the collectionView content size in any other place,
// because you run into race condition issues.
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
// If the cell's size has to be exactly the content
// Size of the collection View, just return the
// collectionViewLayout's collectionViewContentSize.
self.colViewObj.frame = CGRect(x: 0, y: 0,
width: targetSize.width, height: 600)
self.colViewObj.layoutIfNeeded()
// It Tells what size is required for the CollectionView
return self.colViewObj.collectionViewLayout.collectionViewContentSize
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColViewCell", for: indexPath) as! ColViewCell
cell.lblTitle.text = arrData[indexPath.item]
cell.lblTitle.layer.borderColor = UIColor.black.cgColor
cell.lblTitle.layer.borderWidth = 1.0
return cell
}
}
extension String {
func width(withConstraintedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.width)
}
}
Output:
Red Border : UITableViewCell
Yellow Border : UICollectionViewCell
Black Outline : Label
with UICollectionViewDelegateFlowLayout
without UICollectionViewDelegateFlowLayout
Reference:
UICollectionView inside a UITableViewCell -- dynamic height?
Note :
TableViewCell height is based on collectionview content size i.e. if same tableCell have any other UI component other than collectionview or there is top bottom margin for collectionView then it won't be calculated. For this, you can create multiple cells in which one cell only contain collectionview (Best Approach for now) or you can return your actual tableViewCell height in systemLayoutSizeFitting by calculation.
how to give height to cell accorting to text in swift
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
let message = "Swift is a powerful and intuitive programming language for macOS, iOS, watchOS and tvOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love."
let font = UIFont.systemFont(ofSize: 12.0)
let height = heightForLabel(text: message, font: font, width: self.view.bounds.width )
if height > 40 {
return height
} else {
return 40.0;
}
}
func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat
{
let label:UILabel = UILabel(frame: CGRect(x:0,y: 0,width:width,height:CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
Question:
How To Make UITableViewCell Height Dynamic according the UICollectionViewCell?
View Hierarchy:
UIViewController
UITableView
UITableViewCell
UICollectionView
UICollectionViewCell1
Label 1
UICollectionViewCell2
Label 2
UICollectionViewCell3
Label 3
[So on]
Explanation:
Here Label1, Label2, label 3 are have dynamic height and numberOfRows in UICollectionView is also dynamic. I need Height of UITableViewCell according to the UICollectionViewCell.
View Hierarchy In UIViewController
Steps:
Bind Delegate And Datasource
Bind UITableView delegate and datasource with the UIViewController.
Bind UICollectionView Delegate and datasource with the UITableViewCell here TblCell.
In UIViewController
class CollectionVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
:
:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension // For tableCell Dynamic Height
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 200 // For tableCell Estimated Height
}
// Above two delegates must be necessary or you can use property for same.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1 // returning 1, as per current single cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TblCell") as! TblCell
return cell
}
}
In TblCell
class TblCell: UITableViewCell , UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
#IBOutlet var colViewObj: UICollectionView!
// Array for Label
var arrData = ["Hello", "How re you?", "rock the world", "Nice to meet you.", "Hey! It is awsome."]
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.colViewObj.isScrollEnabled = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// Get width of Label As per String characters.
let aWidth : CGFloat = arrData[indexPath.row].width(withConstraintedHeight: 40, font: UIFont.systemFont(ofSize: 17.0))
return CGSize(width: aWidth + 40 , height: 40)
}
// THIS IS THE MOST IMPORTANT METHOD
//
// This method tells the auto layout
// You cannot calculate the collectionView content size in any other place,
// because you run into race condition issues.
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
// If the cell's size has to be exactly the content
// Size of the collection View, just return the
// collectionViewLayout's collectionViewContentSize.
self.colViewObj.frame = CGRect(x: 0, y: 0,
width: targetSize.width, height: 600)
self.colViewObj.layoutIfNeeded()
// It Tells what size is required for the CollectionView
return self.colViewObj.collectionViewLayout.collectionViewContentSize
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColViewCell", for: indexPath) as! ColViewCell
cell.lblTitle.text = arrData[indexPath.item]
cell.lblTitle.layer.borderColor = UIColor.black.cgColor
cell.lblTitle.layer.borderWidth = 1.0
return cell
}
}
extension String {
func width(withConstraintedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.width)
}
}
Output:
Red Border : UITableViewCell
Yellow Border : UICollectionViewCell
Black Outline : Label
with UICollectionViewDelegateFlowLayout
without UICollectionViewDelegateFlowLayout
Reference:
UICollectionView inside a UITableViewCell -- dynamic height?
Note :
TableViewCell height is based on collectionview content size i.e. if same tableCell have any other UI component other than collectionview or there is top bottom margin for collectionView then it won't be calculated. For this, you can create multiple cells in which one cell only contain collectionview (Best Approach for now) or you can return your actual tableViewCell height in systemLayoutSizeFitting by calculation.
how to give height to cell accorting to text in swift
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
let message = "Swift is a powerful and intuitive programming language for macOS, iOS, watchOS and tvOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love."
let font = UIFont.systemFont(ofSize: 12.0)
let height = heightForLabel(text: message, font: font, width: self.view.bounds.width )
if height > 40 {
return height
} else {
return 40.0;
}
}
func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat
{
let label:UILabel = UILabel(frame: CGRect(x:0,y: 0,width:width,height:CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
So, I am right now making an app with a collection view layout and was wondering how to go about designing it to make it look nice. I found a picture online that I would like it to look like and was wondering how I should go about making it.
Here is the picture:
The collection view I would like to replicate is the one in the middle.
Here is how my current cells look like:
My Cells after the first answer:
This is my current code for configuring the cells:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelCell", for: indexPath) as? ChannelCollectionViewCell
let channel = channels[indexPath.row]
// Configure the cell
cell?.configureCell(channel: channel)
return cell!
}
My guess is there would be 2 main things to making the deisgn I want which brings me to two specific questions.
How do I make a cell have rounded corners?
How do I space a cell from the side of screen and reduce gaps between cells?
ViewController Class
class YourClass: UIViewController {
//MARK:-Outlets
#IBOutlet weak var yourCollectionView: UICollectionView!
//Mark:-Variables
var cellWidth:CGFloat = 0
var cellHeight:CGFloat = 0
var spacing:CGFloat = 12
var numberOfColumn:CGFloat = 2
//MARK:-LifeCycle
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
yourCollectionView.contentInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
if let flowLayout = yourCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
cellWidth = (yourCollectionView.frame.width - (numberOfColumn + 1)*spacing)/numberOfColumn
cellHeight = 100 //yourCellHeight
flowLayout.minimumLineSpacing = spacing
flowLayout.minimumInteritemSpacing = spacing
}
}
extension YourClass:UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? YourCollectionViewCell{
//Configure cell
return cell
}
return UICollectionViewCell()
}
}
extension YourClass:UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: cellWidth, height: cellHeight)
}
}
CollectionViewCell Class
class YourCollectionViewCell:UICollectionViewCell{
override func awakeFromNib() {
super.awakeFromNib()
self.layer.cornerRadius = 10 //customize yourself
self.layer.masksToBounds = true
}
}