how to use custom cell in collection view controller in swift 3

不羁的心 提交于 2019-12-13 14:15:28

问题


I am using swift 3 - I know how to show some Images in collection view with custom Cell - the problem is that I can't use custom cell in Collection View Controller

here is the collection view Controller Codes private let reuseIdentifier = "uploadCell"

class uploadedFiles: UICollectionViewController {

var images = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"  ]

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    //myCollectionView.sizeToFit()
    //cell.sizeToFit()


    cell.cellImages.image = UIImage(named: images[indexPath.row])



    return cell
}

and here is the Collection view Cell Code

   import UIKit

  class UICollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var cellImages: UIImageView!
   }

remember that I used "uploadCell" for identifier


回答1:


For using CollectionView Custom Cell

Step 1: Create Subclass of CollectionViewCell

class ImageCell: UICollectionViewCell {
    @IBOutlet weak var imgView: UIImageView!
}

Step 2: set CollectionViewCell class in StoryBoard

Step 3: reuseCollectionView Cell

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

    cell.imgView.image = self.arrMedia[indexPath.row] as? UIImage
    return cell
}



回答2:


UICollectionView implementation is quite interesting. You can quite simple source code and video tutorial from these link :

https://github.com/Ady901/Demo02CollectionView.git

https://www.youtube.com/watch?v=5SrgvZF67Yw

class DummyCollectionCell: UICollectionViewCell {

    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
                cell.titleLabel.text = nameArr[indexPath.row]
                cell.userImageView.backgroundColor = .blue
                return cell
}


来源:https://stackoverflow.com/questions/44257423/how-to-use-custom-cell-in-collection-view-controller-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!