簡體   English   中英

UICollectionView設置默認位置

[英]UICollectionView set default position


我有一個帶有3個單元的CollectionView,它擴展到整個設備的屏幕,基本上代表了我的3個主要視圖。
我啟用了分頁功能,因此它基本上與iOS主屏幕完全一樣。
我的問題是我希望此CollectionView的“默認”位置等於view.frame.width以便第二個Cell是“默認”視圖,我可以左右滑動以進入我的輔助視圖。
我已經試過了

collectionView.scrollToItem()

collectionView.scrollRectToVisible()

以及

collectionView.setContentOffset()

但它們似乎只在視圖加載后才起作用(我通過導航欄中的按鈕嘗試了它們)。 先感謝您!


編輯:
現在這個工作,但我在另一個中間單元格中還有另一個集合視圖,它包含一個小的2頁UICollectionView列表,它實際上來自UICollectionViewCell的子類,名為PersonCell每個子類都持有一個UICollectionView 我希望這些UICollectionViews也可以滾動到索引1,這是我的代碼:

for tabcell in (collectionView?.visibleCells)! {
    if let maincell: MainCell = tabcell as? MainCell {
        for cell in maincell.collectionView.visibleCells {
            if let c = cell as? PersonCell {
                c.collectionView.scrollToItem(at: (NSIndexPath(item: 1, section: 0) as IndexPath), at: [], animated: false)
            }
        }
    }
}

這是在執行viewDidLayoutSubviews我的“根”的CollectionViewController



編輯2:現在我嘗試在MainCell類中使用以下代碼(它是一個UICollectionViewCell子類):

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    let personCell = cell as! PersonCell
    personCell.collectionView.scrollToItem(at: (NSIndexPath(item: 1, section: 0) as IndexPath), at: [], animated: false)
}



編輯3:
簡而言之,我基本上需要一個將單元格添加到UICollectionView 調用的委托方法。

您是否嘗試過[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

嘗試在viewDidLayoutSubviews調用代碼

好的,我明白了!
這個答案給了我最后的暗示:
https://stackoverflow.com/a/16071589/3338129
基本上,現在我只是在Cell初始化后執行此操作:

self.collectionView.alpha = 1
self.data = data // array is filled with data
self.collectionView.reloadData()
DispatchQueue.main.async {
    for cell in self.collectionView.visibleCells {
        (cell as! PersonCell).collectionView.scrollToItem(at: (NSIndexPath(item: 1, section: 0) as IndexPath), at: [], animated: false)
    }
    self.collectionView.alpha = 1
}

基本上,DispatchQueue.main.async {...}中的代碼在下一個UI刷新周期調用,這意味着在單元格已經存在的位置。 為了防止用戶在幾分之一秒內看到錯誤的頁面,我將整個collectionView的alpha設置為0,並在數據存在時立即將其切換,單元格在那里並且頁面已滾動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM