滚动到collectionView到specie索引

时间:2016-10-04 11:25:02

标签: ios uiscrollview uicollectionview swift3 uicollectionviewcell

我有一个collectionView有多个单元格,当我加载它时,我想选择一个特定的单元格,将其显示为选中并将集合视图滚动到所选单元格的位置,而不必进行滚动自己。

我可以将单元格显示为已选中,但滚动似乎不适用于提供的函数。

这是我尝试这样做的。

class RepsCellView: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    lazy var repsValuesCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.black
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false

        return collectionView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }



    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupViews() {

        addSubview(repsValuesCollectionView)

        //...
        //  Cell
        let selectedIndex = IndexPath(item: 19, section: 0)
        repsValuesCollectionView.selectItem(at: selectedIndex, animated: true, scrollPosition: [.centeredHorizontally, .centeredVertically])

    }

    //  CollectionView DataSource Functions
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        return cell
    }
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

您使用什么ViewController事件方法来运行代码?

无论如何,我可以滚动它将你的代码放在ViewController事件方法viewDidAppear方法中。

class CollectionViewController: UICollectionViewController {
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let cellToSelect = IndexPath(item: 99, section: 0)

    self.collectionView?.scrollToItem(at: cellToSelect, at: [.centeredHorizontally, .centeredVertically], animated: true)
  }

  override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RepsCellView
    cell.setupViews() // added this line
    return cell
  }
}