以编程方式将UIImage添加到集合视图单元格中

时间:2017-04-14 14:31:31

标签: ios swift uicollectionview

这是我的集合视图单元格的自定义类:

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

}

然后在我的控制器的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,则单元格会显示,但不显示图像。

我遗失了什么,或者没有正确实施?

2 个答案:

答案 0 :(得分:2)

UICollectionViewCell已经是一个视图,您可以直接向其添加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

答案 1 :(得分:0)

最佳做法是创建原型单元格并在界面构建器中添加图像视图。在这种特定情况下,我认为错误在于您没有将图像视图的框架设置为缩放到单元格框架。

尝试打印图像视图的框架,它可能会显示0,0,0,0。