我一直在关注 youtube 上的代码,其中包含一些我需要在我正在构建的应用程序中使用的功能。但是,我的单元格在 UICollectionView 的 subview 中没有显示。
我已经尝试过修改单元格和 View 的参数,但似乎没有任何效果。
在一个单独的类中:
extension UIView{
func addConstraintsWithFormat(format: String, views: UIView...){
var viewsDictionary = [String:UIView]()
for (index, view) in views.enumerated(){
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewsDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDictionary))
}
}
extension UIColor {
static func rgb(r: CGFloat, g: CGFloat, b: CGFloat, a:CGFloat) -> UIColor{
return UIColor(red: r/255, green: b/255, blue: g/255, alpha: a)
}
}
在 ViewController 类中:
override func viewDidLoad() {
super.viewDidLoad()
setupMenuBar()
}
let menuBar: MenuBar = {
let mb = MenuBar()
return mb
}()
private func setupMenuBar() {
view.addSubview(menuBar)
view.addConstraintsWithFormat(format: "H:|[v0]|", views: menuBar)
view.addConstraintsWithFormat(format: "V:|[v0(60)]", views: menuBar)
}
在为 View 创建的类中:
class MenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.rgb(r: 230, g: 32, b: 31, a: 1)
cv.dataSource = self
cv.delegate = self
return cv
}()
let cellId = "cellId"
override init(frame: CGRect) {
super.init(frame: frame)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
addSubview(collectionView)
addConstraintsWithFormat(format: "H:|[v0]|", views: collectionView)
addConstraintsWithFormat(format: "V:|[v0]|", views: collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.backgroundColor = UIColor.blue
return cell
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我希望单元格显示在菜单栏上,但是当我运行代码时唯一出现的只是红色栏,没有蓝色单元格。
最佳答案
您的问题不在于 Collection View 的框架,因为它是由您使用约束处理的。问题在于这一行:
let layout = UICollectionViewLayout()
来自文档 UICollectionViewLayout
是:
An abstract base class for generating layout information for a collection view
因此它本身不提供正确的布局信息,您应该使用它的子类来提供正确的布局信息。
其中一个示例是 UICollectionViewFlowLayout
,它允许您以基本的网格格式布置单元格。
如果你用这个替换上面的行,那么你会看到单元格:
let layout = UICollectionViewFlowLayout()
然后您可以修改该类提供的参数或创建您自己的 UICollectionViewLayout 子类,提供您需要的布局的详细信息。
关于swift - 单元格内容未显示在 UICollectionView 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56567570/