这是我为 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/