gpt4 book ai didi

swift - View Controller 内的collectionView未显示

转载 作者:行者123 更新时间:2023-11-30 10:35:41 24 4
gpt4 key购买 nike

我正在尝试在 View Controller 中添加一个collectionView。在 View Controller 中,我已经有一些内容,并且我正在尝试将 Collection View 添加为 View Controller 中最后一个内容正下方的 subview 。我不知道还能怎么做。请帮忙。代码如下:

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 中的其他细节显示正常,但只是 Collection View 未在 View Controller 内注册

最佳答案

将其添加到 View 后调用collectionView.reloadData()

关于swift - View Controller 内的collectionView未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58085591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com