ios - 以编程方式将 UIImage 添加到 Collection View 单元格中

标签 ios swift uicollectionview

这是我为 Collection View 单元格自定义的类:

import UIKit

class NavBarCell: UICollectionViewCell {

    var avatarImageView: UIImageView = {
        var avatarView = UIImageView()
        avatarView.contentMode = .scaleAspectFit

        return avatarView
    }()

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

        avatarImageView = UIImageView()
        contentView.addSubview(avatarImageView)
    }

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

}

然后在我的 Controller 的 viewDidLoad

    let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
    navBarCollectionView.setCollectionViewLayout(layout, animated: true)
    navBarCollectionView.backgroundColor = UIColor.clear
    navBarCollectionView.register(NavBarCell.self, forCellWithReuseIdentifier: "cell")
    navBarCollectionView.delegate = self
    navBarCollectionView.dataSource = self
    layout.scrollDirection = .horizontal
    self.navigationController?.navigationBar.addSubview(navBarCollectionView)
    navBarCollectionView.reloadData()

cellForItem 中我有:

        let navBarCell = (collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)) as! NavBarCell

        var image : UIImage = UIImage(named: "TestImage")!
        navBarCell.avatarImageView.image = image
        navBarCell.avatarImageView.layer.borderWidth = 1
        navBarCell.avatarImageView.layer.borderColor = UIColor.getRandomColor().cgColor
        navBarCell.avatarImageView.layer.cornerRadius = 20

        return navBarCell

但是图片浏览量没有显示出来。如果我添加 navBarCell.backgroundColor = UIColor.red 则显示单元格,但不显示图像。

有什么我遗漏或没有正确实现的吗?

最佳答案

UICollectionViewCell 已经是view了,可以直接在上面添加avatarImageView:

addSubview(avatarImageView)

还可以设置约束条件,例如:

avatarImageView.translatesAutoresizingMaskIntoConstraints = false
avatarImageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
avatarImageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
avatarImageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
avatarImageView.heightAnchor.constraint(equalToConstant: 300).isActive = true

关于ios - 以编程方式将 UIImage 添加到 Collection View 单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43413594/

相关文章:

android - Firebase FCM 事务通知(主题与注册 token )

ios - Swift - UIButton 按下时未突出显示

swift - 使用AudioKit框架难以复制Ableton Push MIDI CC功能

ios - CollectionView 默认项目选择

ios - UICollectionView:测量单元格的点击力

ios - 在 reloadItemsAtIndexPaths 之后避免 UICollectionView 的动画

ios - 错误: File not found while importing file from framework

iOS: "Include of non-modular header"与 libxml

ios - 通过按钮调用时 cocoa 动画不触发

ios - 导入我的框架后需要将 UIKit 显式导入项目中的所有 UIKit 子类