我有UICollectionView和两个UIButton:WeekButton和MonthButton。当我触摸WeekButton或MonthButton时,我希望UICollectionView显示我的数据源的最后一个元素。 WeekButton和MonthButton函数之间的区别在于UICollectionView的单元格大小。当我触摸两个按钮中的任何一个时,我调用scrollToItem。当我触摸MonthButton时它工作得很好,但是当我触摸WeekButton时却没有。如果我触摸WeekButton两次就行了。我想知道为什么当我第一次触摸WeekButton时它不起作用
@IBAction func touchWeekButton(_ sender: UIButton) {
dateProcess.isWeek=true
dateProcess.item=historyItem
dateCollectionView.reloadData()
print("touchWeekButton")
scrollToBottom()
}
@IBAction func touchMonthButton(_ sender: UIButton) {
dateProcess.isWeek=false
dateProcess.item=historyItem
dateCollectionView.reloadData()
scrollToBottom()
}
func scrollToBottom(){
let maxIndexPath=IndexPath(row: dateProcess.colorArray.count-1, section:0 )
self.dateCollectionView.scrollToItem(at: maxIndexPath, at: UICollectionViewScrollPosition.bottom, animated: false)
}
扩展HistoryViewController:UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if dateProcess.isWeek==true{
let colViewHeight=collectionView.bounds.height
let colViewWidth=collectionView.bounds.width
let cellWidth=colViewWidth/7-1
let cellHeight=colViewHeight/4
return CGSize(width: cellWidth, height: cellHeight)
}else{
let colViewHeight=collectionView.bounds.height
let colViewWidth=collectionView.bounds.width
let cellWidth=colViewWidth/31
let cellHeight=colViewHeight/16
return CGSize(width: cellWidth, height: cellHeight)
}
}
}
答案 0 :(得分:4)
可能你需要等到你的collectionView重新加载,然后才能滚动到任何项目。你可以这样做:
@IBAction func touchWeekButton(_ sender: UIButton) {
dateProcess.isWeek=true
dateProcess.item=historyItem
dateCollectionView.reloadData()
print("touchWeekButton")
DispatchQueue.main.async {
scrollToBottom()
}
}
@IBAction func touchMonthButton(_ sender: UIButton) {
dateProcess.isWeek=false
dateProcess.item=historyItem
dateCollectionView.reloadData()
DispatchQueue.main.async {
scrollToBottom()
}
}