![](/img/trans.png)
[英]UICollectionView scrollToItem not working in .rightToLeft app
[英]UICollectionView scrollToItem Not Working in iOS 14
我正在使用集合視圖 UICollectionView,它工作得非常好……除了我無法滾動到任何特定項目。 它似乎總是滾動到“中間”是我最好的猜測。 無論如何,我發送給 scrollToItem 的任何內容似乎都對滾動沒有影響。 我已將它放在整個視圖控制器的各個位置,但沒有成功。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let lastIndex = IndexPath(row: messages.count-1, section: 0)
self.messagesView.scrollToItem(at: lastIndex, at: .bottom, animated: true)
}
UICollection View 在 iOS 14 中存在帶有scrollToItem 的錯誤。 在 iOS 14 中,它僅在集合視圖分頁被禁用時才有效。 所以如果我們必須手動和以編程方式滾動,我得到了一個解決方案。
特別適用於 iOS 14
self.collView.isPagingEnabled = false
self.collView.scrollToItem(at: IndexPath(item: scrollingIndex, section: 0), at: .left, animated: true)
self.collView.isPagingEnabled = true
您可以嘗試將滾動代碼放在viewDidLayoutSubviews
,它應該在加載所有表格單元格后調用,這意味着您的 messages.count 應該可以工作。 此外,請確保您的集合視圖中只有一個部分。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.scrollToBottom()
}
func scrollToBottom() {
DispatchQueue.main.async {
let lastIndex = IndexPath(item: messages.count-1, section: 0)
self.messagesView.scrollToItem(at: lastIndex, at: .bottom, animated: true)
}
}
斯威夫特 5 / iOS 15
我遇到了同樣的問題,所以我嘗試了這個單行代碼並完成了它。
// here we slect the required cell instead of directly scrolling to the item and both work same.
self.collectionView.selectItem(at: IndexPath(row: self.index, section: 0), animated: true, scrollPosition: .left)
如果您希望啟用分頁,這對我有用:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.isPagingEnabled = false
collectionView.scrollToItem(
at: IndexPath(item: 1, section: 0),
at: .centeredVertically,
animated: false
)
collectionView.isPagingEnabled = true
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.