为什么只更新了第一个单元格中的图像,而未更新uicollectionview中的其余单元格。 ios swift

时间:2018-02-28 10:27:48

标签: ios swift uicollectionview uicollectionviewcell

我试图在顶栏上获得3个图标。

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)
}

因此,只有第一个单元格才会显示地球。 即使我可以改变背景颜色,其余的2个单元格都是空的。

SectionHeader是一个笔尖 enter image description here

1 个答案:

答案 0 :(得分:1)

imageView是单元格的子视图,需要与我看到的大小一致。因此它需要将其框架(其相对于其超视图坐标系的位置 - 单元格)设置为具有原点(0,0)的单元格的高度和宽度。单元格的边界提供了这些尺寸,因此答案可以是

cell.imageView.frame = cell.bounds

或更好

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