【发布时间】:2016-12-18 07:33:16
【问题描述】:
场景 - 我必须以编程方式创建一个自定义 UICollectionView 类,该类必须显示在我想要的任何地方。
到目前为止的代码 -
用于自定义 UICollectionView
class ABSegmentView: UICollectionView,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource {
var segmentProperties=segmentControlProperties()//segmentControlProperties is a modal class having relevant details regarding about population of collection view.
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
self.dataSource = self
self.delegate = self
self.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifier")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(segmentProperties.titleArray)
return segmentProperties.titleArray.count//data properly being received over here
}
//not getting called
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = self.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath)
cell.backgroundColor = UIColor.redColor()
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
return CGSizeMake(self.segmentProperties.segmentHeight, self.segmentProperties.segmentWidth)
}
}
在某个地方添加此集合视图的代码 -
let segment = ABSegmentView(frame: CGRectMake(0, 0, 200, 200), collectionViewLayout: UICollectionViewLayout())
segment.segmentProperties.segmentWidth = 60
segment.segmentProperties.segmentHeight = 50
segment.segmentProperties.titleArray = ["heyy","heyy","heyy","heyy","heyy","heyy"]
self.view.addSubview(segment)
所以添加的只是一个空的集合视图。
找出原因 -
在调试时我发现我的数据源方法cellForItemAtIndexPath() & func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) 没有被调用。
问题 - 我不确定我为所需场景所做的操作是否正确。如果我在某处遗漏了什么或可能是我的错误,请修改我。
编辑:
回答 -
感谢桑托什的回答。我发现我误解了collectionViewLayout的概念。
调查结果 -
-
我必须为集合视图设置适当的流布局作为 具有正确间距和其他值的正确流布局相当 对于正确放置集合视图至关重要。
CollectionView Flow layout 是collection view 的UI,即网格视图。
StackOverflow 中有很多问题是由于 collectionViewFlowLayout 布局不当而导致数据源方法没有被调用。
参考文献除了接受的答案外,对我有用 -
https://stackoverflow.com/a/14681999/5395919
可能遇到此类问题的其他情况 -
-当我们将单元格大小设置为比集合视图大得多时。
-当我们的单元格布局尺寸太大或集合视图不适当时。
【问题讨论】:
-
在将段添加为子视图后,我会调用
segment.reloadData()。 -
@SeNeO 不,它不起作用
标签: ios swift uicollectionview