为什么图像未加载到自定义集合视图单元格中?

时间:2019-12-16 16:24:58

标签: uicollectionviewcell

为什么图像未加载到自定义集合视图单元格中?代码如下:

''' 导入UIKit

ViewController类:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {

var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    let flowLayout = UICollectionViewFlowLayout()
    collectionView = UICollectionView.init(frame: view.bounds, collectionViewLayout: flowLayout)
    collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    collectionView.backgroundColor = .gray
    collectionView.alwaysBounceVertical = true
    view.addSubview(collectionView)

    collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

    collectionView.dataSource = self
    collectionView.delegate = self

}

//MARK: CollectionView Data soure
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10
}

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
    cell.imageView.image = #imageLiteral(resourceName: "person1")
    return cell

}

}

'''

''' 导入UIKit

CollectionViewCell类:UICollectionViewCell {

let bgView = UIView()
let imageView = UIImageView()

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

    self.clipsToBounds = true
    self.autoresizesSubviews = true
    self.backgroundColor = UIColor.blue
    self.layer.cornerRadius = 12

    bgView.frame = self.bounds
    bgView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    bgView.backgroundColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
    //self.addSubview(bgView),所有的View都有backgroundView属性,这个比addSubview更好
    self.backgroundView = bgView

    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    imageView.layer.cornerRadius = 12
    imageView.layer.borderWidth = 6
    imageView.layer.borderColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
    imageView.clipsToBounds = true
    self.addSubview(imageView)

}

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

}

'''

0 个答案:

没有答案