今天測(cè)試提了一個(gè)bug,說(shuō)點(diǎn)擊下一題的時(shí)候,界面沒有刷新題目,還在老題目那里,我說(shuō)不可能啊,我這邊好好的,后來(lái)一看,她的機(jī)子是iOS 14的,我說(shuō)那我適配一下好了。
我的界面層級(jí)是一個(gè)大的collectionView占據(jù)頁(yè)面,里面的cell的大小跟collectionview的bounds一樣大。
下面是我的collectionview創(chuàng)建代碼
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NavigationContentTop - SafeAreaInsetsConstantForDeviceWithNotch.bottom - 60)
layout.sectionInset = UIEdgeInsets.zero
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.xh_register(XHOEWebParentCollectionViewCell.self)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.isScrollEnabled = false
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
} else {
self.automaticallyAdjustsScrollViewInsets = false
}
return collectionView
}()
我滾動(dòng)頁(yè)面調(diào)用的代碼
self.collectionView.scrollToItem(at: IndexPath(item: collectionViewIndex, section: 0), at: .right, animated: true)
結(jié)果找了半天原因沒找到,因?yàn)榭雌饋?lái)很正常,查閱網(wǎng)上的資料,發(fā)現(xiàn)調(diào)用無(wú)效大多是在collectionView尚未布局的時(shí)候就調(diào)用了scrollToItem(at: _, at: _, animated: _),跟我的情況不符合
后來(lái)想著先用setContentOffset(_, animated: _)試試,后來(lái)發(fā)現(xiàn)確實(shí)可以,但是滾動(dòng)的頁(yè)數(shù)越多,發(fā)現(xiàn)cell偏移也越厲害,查看View hierarchy,發(fā)現(xiàn)是cell之間有10的間距,應(yīng)該是沒有設(shè)置flowLayout的minimumLineSpacing屬性。調(diào)整為0后,重新運(yùn)行,正常了
但是按理來(lái)說(shuō)沒有設(shè)置minimumLineSpacing不該影響collectionView的跳轉(zhuǎn)才對(duì),于是繼續(xù)檢查collectionView的設(shè)置,發(fā)現(xiàn)一句可能會(huì)影響的代碼
collectionView.isPagingEnabled = true
我們查看isPagingEnabled的文檔
Discussion
If the value of this property is true, the scroll view stops on multiples of the scroll view’s bounds when the user scrolls. The default value is false.
文檔中解釋說(shuō)scroll view會(huì)停止在scroll view的bounds的整數(shù)倍的位置
那么如果沒有設(shè)置minimumLineSpacing(這里我的collectionView是水平滾動(dòng)的,所以應(yīng)該只用設(shè)置這個(gè)屬性就可以了),那么collectionView在通過scrollToItem(at: _, at: _, animated: _)滾動(dòng)到指定頁(yè)的時(shí)候,實(shí)際上并沒有滾動(dòng)整數(shù)倍的scroll view’s bounds ,和isPagingEnabled屬性相違背,所以說(shuō)到這里,這個(gè)bug其實(shí)有兩個(gè)解決方式
- collectionView.isPagingEnabled = false
- 設(shè)置minimumLineSpacing為0即可
我把minimumLineSpacing的設(shè)置取消掉,單改為isPagingEnabled = false,測(cè)試通過,說(shuō)明推論是應(yīng)該正確的。
2020.11.16 更新
最新發(fā)現(xiàn)在iPad上有collectionview在設(shè)置了minimumLineSpacing = 0后調(diào)用scrollToItem(at: _, at: _, animated: _)仍然無(wú)效,建議設(shè)置了collectionView.isPagingEnabled = true的改用setContentOffset進(jìn)行跳轉(zhuǎn)。