UICollectionView ScrollTo崩溃

时间:2017-06-09 03:17:45

标签: swift uiview swift3 uiscrollview uicollectionview

我试图在我的自定义UIView中使用我的UICollectionView,当在主VC中按下按钮时能够滚动到页面。不幸的是,每当我调用方法在MainVC中执行它时,它就会崩溃,@ to 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()我的理解在哪里出错?

1 个答案:

答案 0 :(得分:1)

问题出在2 as IndexPathIndexPath不是Integer,因此您需要使用其初始值IndexPath制作init(item:section:)的对象。然后以这种方式滚动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's项目从0索引处开始,因此如果您想要滚动到第二项,请使用indexPath生成IndexPath(item: 1, section: 0),因为{ {1}}会在2nd的第3个单元格滚动。