【发布时间】:2016-04-23 04:07:40
【问题描述】:
我有一个UITableView,其中包含UIStackView 的自定义单元格。作为准备新单元格的一部分,当表格视图通过其cellForRowAtIndexPath 方法添加新单元格时,它会实例化并添加任何需要添加到单元格堆栈中的集合视图(MultaCollectionView 类型)和任何UILabel视图(一个单元格可能包括各种集合视图)。理论上,堆栈视图包含一系列标签和集合视图。
虽然标签显示正确,但集合视图在运行时并未显示。我试图显示的集合视图是在 .xib Interface Builder 文档中定义的。
Collection View 的 numberOfSectionsInCollectionView 方法被调用,但 collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) 方法从未被调用。
为什么从未调用过collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) 方法?为什么集合视图不在 Stack View 中呈现?
import UIKit
private let reuseIdentifier = "Cell"
class MultaCollectionView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
self.dataSource = self
}
class func instanceFromNib() -> UICollectionView {
return UINib(nibName: "multas", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UICollectionView
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
return cell
}
}
父TableView通过以下方法添加Cells:
func addSubviewsToCellStack(cell: ArticuloTableViewCell, texto: [[String: String]]) {\
if isLabel == true {
let label = UILabel()
label.text = "blah"
subview = label
cell.textoStack.addArrangedSubview(subview)
} else {
let colview = MultaCollectionView.instanceFromNib()
cell.textoStack.addArrangedSubview(colview)
}
}
}
【问题讨论】:
-
可能是您没有正确设置单元格的项目大小。请设置 CollectionView 范围内每个单元格的项目大小,然后检查!
-
尝试将集合视图的背景颜色设置为 UIColor.greenColor,这样您就可以验证它的大小不是零像素。
-
愚蠢的建议:做
self.collectionView.delegate = self而不是self.delegate。