I am new to both iOS and Swift. I have created a collection view, and it works fine but I want to display multiple items in a single row. I tried but its not working. Can some one help me? Thanks in advance.
This is my code:
DashBoardCollectionVC
import UIKit
class DashBoardCollectionVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var main_collection_view: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = main_collection_view.dequeueReusableCell(withReuseIdentifier: "identify_collection_cell", for: indexPath) as! DashboardCollectionViewCell
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var collectionViewSize = collectionView.frame.size
collectionViewSize.width = collectionViewSize.width/2.0 //Display Three elements in a row.
collectionViewSize.height = collectionViewSize.height/4.0
return collectionViewSize
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Item Clicked : \(indexPath.item)")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}
}
it looks like this
ContainerView Design
I want to display two items in a row. How can I achieve that?
I had a very similar problem some time ago, and it was in the collectionViewLayout method. My cells were completely square, so maybe this doesn't help you, or maybe you can adapt it. This is what worked for me:
Or if we want 2 in a row the code would be:
Also, in storyboard normally when you drag a "collection view" from the object library, the cell appear in the left corner, something like in the next image - Maybe this is not relevant and you can set everything programatically, but just in case is creating some conflicts with the autolayout.