E. Huckabee
E. Huckabee

Reputation: 1818

Swift 3 How to display different data for each item in index UICollectionView

I made a UICollectionView in my app but I can't figure out how to display different data for each cell I'm stuck with the same image I set it to in storyboard

the searching I've done has not resulted in any tutorials but I know that I customize my data in the UICollectionViewCell custom class

class CollectionViewCell: UICollectionViewCell {
    //drawing a blank here...
}

if you could help me out I just want to put a button, two images and a couple labels (2-3) for each cell (there will be about 12 cells and I need them to have different data for each because i am trying to make a character selection screen)

with my current setup

class CharacterViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

var array = [UIImage(named: "ideal image"),UIImage(named: "ideal image"),UIImage(named: "ideal image")]

override func viewDidLoad() {
    super.viewDidLoad()


    // Do any additional setup after loading the view.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FirstCollectionViewCell", for: indexPath) as! FirstCollectionViewCell

    return cell
}

}

i am able to display three of the exact same image but i need the cells to have separate customizable data i know all about .xib files and cocoa touch classes i use em all the time

one site i saw suggested using .xib files for each cell which i dont mind setting up but i need to know how to register the .xib files to be displayed as a cell if you know how could you help me out?

here is my cell

image for cell

you guys are a huge help i think i know how to do it

  1. make cells with custom .xib files
  2. register .xib cells to array
  3. load array of cells into collectionView
  4. enjoy custom collectionView

Upvotes: 3

Views: 3171

Answers (3)

cole
cole

Reputation: 3357

There are more than 1 way to achieve it. Bu your code it seems customcell is used The code for it

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell

      cell.backgroundColor = UIColor.white

         if indexPath.section == 0 {

      cell.imageView.image = image
                }
         if indexPath.section == 1 {

      cell.imageView.image = image
                }
      return cell
 }

override func numberOfSections(in collectionView: UICollectionView) -> Int {
              return 2 // whatever you want
}

         //2
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

         return searches[section].searchResults.count // if each section have same cell

         if section == 0 {
                return 2
            } else if section == 1 {
                return 3
         }
}

Link to customcell for collectionview

Upvotes: 2

Tung Vu Duc
Tung Vu Duc

Reputation: 1662

Here's an example you can follow :

class CollectionViewCell: UICollectionViewCell {

let myButton : UIButton = {
    let btn = UIButton(type: .system)
    btn.translatesAutoresizingMaskIntoConstraints = false
    btn.setTitle("My button", for: .normal)
    return btn
}()

override init(frame: CGRect){
    super.init(frame: frame)
    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setupViews(){
    // Add subViews to your custom cell
    addSubview(myButton)
    myButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    myButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    myButton.widthAnchor.constraint(equalToConstant: 200).isActive = true
    myButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}

}

Next step, you have to register cell class like this in viewDidLoad:

collectionView.register(CollectionViewCell.self, forCellReuseIdentifier: "customCell")

Last step, in cellForItemAt function you define :

let cell = collectionView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomViewCell
        return cell

Upvotes: 0

Jaime Sendra Domenech
Jaime Sendra Domenech

Reputation: 54

In your controller you have to set this:

    Class yourController : UIViewController,UICollectionViewDelegate, UICollectionViewDataSource{...
 //at some point 
yourCollectionView.delegate = self
yourCollectionView.dataSource = self

and then you include this method and you'll be able to load the data you want in each cell:

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: yourCell = collection.dequeueReusableCell(withReuseIdentifier: nameCelda, for: indexPath) as! yourCell
//dataArrayOrWhatever -> An array of data for each row
        let dataForCelll =  dataArrayOrWhatever[indexPath.row]
//functions defined on your yourCell.Swift
        cell.setImage(imageName: someMethodWithDataForImage(data: dataForCell))
        cell.setTitle(title: someMethodWithDataForTitle(data: dataForCell))

Hope it helps you ;)

Upvotes: 2

Related Questions