【发布时间】:2017-12-09 11:16:50
【问题描述】:
我有一个不同时期(每年)的 collectionView 供用户选择。每个项目的大小等于 collectionView 本身的大小。
@IBOutlet weak var periodCollectionView: UICollectionView!
@IBOutlet weak var itemLabel: UILabel!
let collectionValues = ["Day", "Week", "Month", "Year"]
var currentVisibleItem: Int?
override func viewDidLoad() {
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PeriodName", for: indexPath) as? DisplayPeriodCollectionViewCell
else {
fatalError("Unable to cast collection view cell as DisplayPeriodCollectionViewCell")
}
cell.periodName.text = collectionValues[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = collectionView.frame.height
let width = collectionView.frame.width
return CGSize(width: width, height: height)
}
我想要做的是获取一个信息标签,以在 collectionView 滚动后显示当前可见项目的索引。她是代码:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let centerPoint = CGPoint(x: periodCollectionView.center.x + periodCollectionView.contentOffset.x, y: 1.0)
print("centerPoint: \(centerPoint)")
if let currentItemIndexPath = periodCollectionView.indexPathForItem(at: centerPoint) {
currentVisibleItem = currentItemIndexPath.item
print("index of current item: \(currentVisibleItem!)")
itemLabel.text = "\(currentVisibleItem!)"
} else {
print("could not get index of current item...")
}
}
我添加了打印语句来检查值是否在运行时正确定义,它们显示一切正常。问题是标签在滚动结束后并不总是更新其文本,而是等待新的滚动发生:
我不知道为什么会这样 - 在scrollViewDidEndDecelerating 设置断点表明所有代码都已执行,那么标签文本有什么问题?
UPD。未更新标签文本似乎是模拟器问题 - 在设备上运行时,标签会正确更新。
【问题讨论】:
-
scrollViewDidEndScrollingAnimation(_:)工作得更好吗? -
我不会仅仅依赖模拟器问题。这可能只是时间问题,您只是在设备上看不到它,但它可能发生在速度较慢/速度较快的设备上。
-
问题是每次集合视图滚动时都会执行所有代码 - 包括标签更新。我用断点检查了它。但在模拟器上,标签更新由于某种原因没有显示。
-
我已经看到了在之前滚动的滚动视图中更新标签的问题。我想知道滚动动画是否在模拟器上尚未完成,但在您尝试更新标签时已在设备上完成。你试过
scrollViewDidEndScrollingAnimation吗? -
scrollViewDidEndScrollingAnimation根本不起作用 - 无论是在控制台(打印语句)还是在模拟器中。
标签: ios swift uiscrollview uicollectionview