問題描述
CollectionViewCell 未出現在 collectionView 中 (CollectionViewCell not appearing in collectionView)
我有一個問題,自定義 UICollectionViewCell
不會出現在 UICollectionView
中。有人知道我錯過了什麼嗎?我提前感謝它。
下面是我的 UICollectionViewController:
private let reuseIdentifier = "FeedCell"
class FeedViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
// MARK: Properties
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.register(FeedCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
//MARK: ‑ UICollectionViewFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) ‑> CGSize {
let width = view.frame.width
return CGSize(width: width, height: width)
}
//MARK: ‑ UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) ‑> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) ‑> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) ‑> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FeedCell
print("CELL")
cell.backgroundColor = .black
return cell
}
//FEED CELL
class FeedCell: UICollectionViewCell {
//MARK: ‑ Properties
let profileImageView: CustomeImageView = {
let imageView = CustomeImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.backgroundColor = .lightGray
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .red
print("feedcell1")
addSubview(profileImageView)
profileImageView.anchor(top: topAnchor, bottom: nil, left: leftAnchor, right: nil, paddingTop: 8, paddingBottom: 0, paddingLeft: 8, paddingRight: 0, width: 40, height: 40)
profileImageView.layer.cornerRadius = 40/2
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
謝謝:)
參考解法
方法 1:
The issue was I had previously instantiated FeedViewController with
FeedViewController(collectionViewLayout: UICollectionViewLayout())
instead of `FeedViewController(collectionViewLayout:
UICollectionViewFlowLayout()))` since FeedViewController has
UICollectionViewDelegateFlowLayout
protocol.
(by Nouru Muneza、Nouru Muneza)