方案 - 我必須以編程方式創建自定義的UICollectionView類,該類必須呈現在我想要的任何位置。在自定義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流佈局就是放置收集視圖的UI(即網格視圖)。
StackOverflow中存在很多問題,這些問題涉及數據源方法由於collectionViewFlowLayout鋪設不當而未被調用。
參考,從接受的答案除了摸索出適合我 -
https://stackoverflow.com/a/14681999/5395919
其他情況下,當某些人能遇到這樣的問題 -
- 當我們設置我們的細胞大小比我們的收集視圖更大。
- 當我們的單元格佈局尺寸太大或沒有被收集視圖適當保留時。
我會叫'segment.reloadData()'添加段後一個子視圖。 – SeNeO
@SeNeO不,它不起作用 –