這是我收集觀察室自定義類:編程方式添加的UIImage到收集觀察室
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
,那麼單元顯示出來,但不是圖像。
任何我失蹤,或不正確實施?
您需要設置'avatarImageView'的初始化幀。如果你想讓imageView縮放到單元格框架,可以在'cellForItem'處重置框架或使用約束。 – Ayazmon