我试图在我的自定义 UIView 中使用我的 UICollectionView,当在主 VC 中按下按钮时能够滚动到页面。不幸的是,每次我在 MainVC 中调用该方法时,它都会崩溃,@到 scrollToItem。
这是我的 MainVC。
let mainView = MainViewsHome()
在 ViewWillAppear 中:
/** Setting up the bottom half **/
mainView.frame = CGRect(x:self.view.frame.width * 0, y:self.view.frame.height / 6.2, width:self.view.frame.width,height:self.view.frame.height / 1.1925)
mainView.backgroundColor = UIColor.clear
self.view.addSubview(mainView)
&& 我的自定义 UIView
class MainViewsHome: UIView, UIGestureRecognizerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var cellId = "Cell"
var collectionView : UICollectionView!
override init(frame: CGRect) {
super.init(frame: CGRect(x:0, y:0, width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 1.3))
/**Creation of the View **/
let flowLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flowLayout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect(x:self.frame.width * 0,y:self.frame.height * 0,width:self.frame.width,height: self.frame.height), collectionViewLayout: flowLayout)
collectionView.register(uploadGenreSelectionCVC.self, forCellWithReuseIdentifier: cellId)
collectionView.isPagingEnabled = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.purple
self.addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func moveToPage() {
print("we are moving to page")
self.collectionView.scrollToItem(at: 2 as IndexPath, at: UICollectionViewScrollPosition.right, animated: true)
}
&& 然后在我的 MainVC 中调用:mainView.moveToPage()
我的理解哪里出错了?
最佳答案
问题出在 2 作为 IndexPath
,IndexPath
不是 Integer
所以你需要使用它的初始化 init(item:section:)
来创建 IndexPath
的对象。然后以这种方式将 collectionView
滚动到特定项目。
func moveToPage() {
let indexPath = IndexPath(item: 2, section: 0) //Change section from 0 to other if you are having multiple sections
self.collectionView.scrollToItem(at: indexPath, at: .right, animated: true)
}
注意 CollectionView 的
项目从0
索引开始所以如果你想滚动到第二个项目然后制作indexPath
使用 IndexPath(item: 1, section: 0)
因为 2nd
将滚动到 collectionView
的第三个单元格。
关于swift - UICollectionView ScrollTo 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448735/