1.?使用scrollToItem
方法滾動集合視圖
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
let firstIndexPath = IndexPath(item: 0, section: 0)
let lastIndexPath = IndexPath(item: self.recordArray.count - 1, section: 0)
// Scroll to first item
self.collectionView.scrollToItem(at: firstIndexPath, at: .left, animated: false)
// Delay for a short time (e.g., 0.1 seconds)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// Scroll to last item
self.collectionView.scrollToItem(at: lastIndexPath, at: .left, animated: false)
}
}
上述代碼中,首先使用scrollToItem
方法將集合視圖滾動到第一條數(shù)據(jù)(左側(cè)對齊),然后在稍后的延遲時(shí)間后,再次使用scrollToItem
方法將其滾動到最后一條數(shù)據(jù)(左側(cè)對齊)。
2. 使用setContentOffset
方法來滾動集合視圖
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
let firstIndexPath = IndexPath(item: 0, section: 0)
let lastIndexPath = IndexPath(item: self.recordArray.count - 1, section: 0)
if let firstCellAttributes = self.collectionView.layoutAttributesForItem(at: firstIndexPath),
let lastCellAttributes = self.collectionView.layoutAttributesForItem(at: lastIndexPath) {
let contentOffset = CGPoint(x: lastCellAttributes.frame.origin.x - firstCellAttributes.frame.origin.x,
y: 0)
self.collectionView.setContentOffset(contentOffset, animated: false)
}
}
上述代碼中,我們使用了setContentOffset
方法來滾動集合視圖。我們獲取了第一條數(shù)據(jù)和最后一條數(shù)據(jù)的布局屬性,然后根據(jù)它們的位置計(jì)算出正確的contentOffset
值,使得集合視圖能夠滾動到最后一條數(shù)據(jù)。
3. 使用scrollRectToVisible
方法進(jìn)行滾動集合視圖文章來源:http://www.zghlxwxcb.cn/news/detail-614378.html
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
let firstIndexPath = IndexPath(item: 0, section: 0)
let lastIndexPath = IndexPath(item: self.recordArray.count - 1, section: 0)
if let firstCellAttributes = self.collectionView.layoutAttributesForItem(at: firstIndexPath),
let lastCellAttributes = self.collectionView.layoutAttributesForItem(at: lastIndexPath) {
let firstRect = firstCellAttributes.frame
let lastRect = lastCellAttributes.frame
let visibleRect = CGRect(x: lastRect.origin.x, y: 0, width: self.collectionView.bounds.width, height: self.collectionView.bounds.height)
self.collectionView.scrollRectToVisible(visibleRect, animated: false)
}
}
在上述代碼中,我們使用了scrollRectToVisible
方法來滾動集合視圖。我們獲取了第一條數(shù)據(jù)和最后一條數(shù)據(jù)的布局屬性,并根據(jù)它們的位置計(jì)算出一個(gè)可見的矩形區(qū)域,然后將該矩形區(qū)域滾動到可見范圍內(nèi)。文章來源地址http://www.zghlxwxcb.cn/news/detail-614378.html
到了這里,關(guān)于Swift 讓ScrollView滾動到具體某個(gè)位置的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!