我正在尝试在视图控制器中添加collectionView。在视图控制器中,我已经有一些内容,并且我试图在视图控制器中最后一个内容的正下方添加一个集合视图作为子视图。我不确定该怎么做。请帮忙。这是下面的代码:
import UIKit
class StoreDetailViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
func configureUI() {
view.backgroundColor = .white
navigationItem.title = "Store"
let imageView: UIImageView = {
let image = UIImageView()
image.image = UIImage(named: "store")
image.contentMode = .scaleAspectFill
image.layer.cornerRadius = 16
image.layer.masksToBounds = true
return image
}()
let nameLabel: UILabel = {
let name = UILabel()
name.font = UIFont.systemFont(ofSize: 16, weight: .heavy)
name.text = names
name.numberOfLines = 2
name.textColor = .primaryDark
return name
}()
let descriptionLabel: UILabel = {
let description = UILabel()
description.font = UIFont.systemFont(ofSize: 12, weight: .medium)
description.text = desc
description.numberOfLines = 5
description.textColor = .primaryDark
return description
}()
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translateAll()
cv.delegate = self
cv.dataSource = self
cv.register(StoreProductsCell.self, forCellWithReuseIdentifier: "cellId")
cv.backgroundColor = .red
return cv
}()
view.addSubview(imageView)
view.addSubview(nameLabel)
view.addSubview(descriptionLabel)
view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! StoreProductsCell
cell.backgroundColor = .blue
return cell
}
}
我也已经添加了约束,但是我没有在代码中包含约束。 vc中的其他详细信息显示正常,但只是集合视图未在视图控制器中注册
答案 0 :(得分:0)
将collectionView.reloadData()
添加到视图后,调用它。