Ng Zhong Qin
Ng Zhong Qin

Reputation: 1261

Why is only image in first cell updated while the rest of the cells in uicollectionview not updated. ios swift

I'm trying to get 3 icons on the top bar.

enter image description here

  import UIKit

  class SectionHeader: UICollectionReusableView {

private let telButtonCellId = "TelButtonCell"
private let searchBarCellId = "SearchBarCell"
private let notificationButtonCellId = "NotificationButtonCell"

// MARK: - Properties

@IBOutlet weak var collectionView: UICollectionView!

// MARK: - Initialization



override func awakeFromNib() {
    super.awakeFromNib()
    self.collectionView.register(UINib(nibName:notificationButtonCellId, bundle: nil), forCellWithReuseIdentifier: notificationButtonCellId)

    self.collectionView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width*0.2) // this is need to set the size of the collection view
    self.collectionView.delegate = self
    self.collectionView.dataSource = self

}


extension SectionHeader : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: notificationButtonCellId, for: indexPath) as! NotificationButtonCell
    var image = UIImage(named: "globe")
    cell.imageView.image=image?.addImagePaddingShift(x: 20 , y: 20,shiftX: 0, shiftY: 10)
    cell.imageView.contentMode = .scaleAspectFit
    cell.imageView.bounds=cell.bounds
    cell.imageView.center = cell.center;
    cell.backgroundColor = UIColor.lightGray

    return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let frameWidth = UIScreen.main.bounds.width
    let frameHeight = UIScreen.main.bounds.width*0.2

    return CGSize(width: frameWidth*0.15, height: frameHeight*1.0)
}

So only the first cell will have the globe displayed. the rest of the 2 cells are empty even though i can change the background colour.

The SectionHeader is a nib enter image description here

Upvotes: 0

Views: 95

Answers (1)

surToTheW
surToTheW

Reputation: 832

The imageView is subview of the cell, that needs to be with its size as I see. So it needs its frame (its position in relation to its superview coordinate system - the cell) to be set to the height and width of the cell with origin (0,0). The bounds of the cell provide these dimensions so the answer can be

cell.imageView.frame = cell.bounds

or better

cell.imageView.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)

Upvotes: 1

Related Questions