模仿原生的IOS的calendar写一个程序。
年份表示使用UICollectionView。
UICollectionView页面滑动reloadData之后,Sections里的cell顺序变乱。
开始的时候,顺序是正确的。
当向上或向下滚动的时候。月份的顺序就会变乱。
下面是代码
数据源的代码
// 定义展示的Section的个数
func numberOfSections(in collectionView: UICollectionView) -> Int {
return _years.count;
}
// 定义展示的UICollectionViewCell的个数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _years[section].months.count;
}
//每个UICollectionView的头部
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == "UICollectionElementKindSectionHeader"{
let indexYear = _years[indexPath.section];
let calendarAnnualHeaderView :CalendarAnnualHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "AnnualHeaderView", for: indexPath) as! CalendarAnnualHeaderView
calendarAnnualHeaderView.yearlabel.text = String(indexYear.value)
return calendarAnnualHeaderView
} else {
return UICollectionReusableView()
}
}
//每个UICollectionView展示的内容
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let indexYear = _years[indexPath.section];
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AnnualCell", for: indexPath) as! CalendarAnnualCell
cell._month = indexYear.months[indexPath.row]
return cell
}
滑动的处理代码
func scrollViewDidScroll(_ scrollView: UIScrollView){
// 向下滑动
if (scrollView.contentOffset.y + view.frame.size.height >= scrollView.contentSize.height ){ // Loads more videos
let currentLastYear = _dataSource?._years.last
let year = (currentLastYear?.value)! + 1
_dataSource?._years.append(YearNode(value: year))
_yearView.reloadData()
}
// 向上滑动
if scrollView.contentOffset.y <= 0.0 {
let currentLastYear = _dataSource?._years.first
let year = (currentLastYear?.value)! - 1
_dataSource?._years.insert(YearNode(value: year), at: 0)
_yearView.reloadData()
_yearView?.contentOffset.y = ( _yearView?.bounds.size.height)!
}
}
大家可以帮忙看一下是哪里的问题吗。
刚刚接触IOS。可能有些地方描述的不准确,见谅。
最后,谢谢。
scrollViewDidScroll
是只要collectionView滑动就会调用, 当collectionView
, 向上或者向下滑动时,scrollViewDidScroll
会多次调用, 也就是说year
一直在增或者减. 每次滑动year
都在变化,显示的month
不是同一year
的.