首页 > 解决方案 > UICollectionView 保持水平列表滚动位置

问题描述

UICollectionViewCellUICollectionView.

我的问题是,如果我horizontal list将第一个单元格中的滚动到另一个位置,第四个单元格也将位于同一位置。

第二个和第五个,第三个和第六个都一样……

也不keep horizontal scroll position要从纵向到横向或相反。

有没有办法让UICollectionView牢房里的人保持他们的位置?

更新 2:

我知道我必须将内部horizontal集合视图保存content offsets在一个数组中。我在下面的链接中读到了这一点,但在下面的链接中,他们希望在UITableViewand中实现这一点UIScrollView。我想在UICollectionView里面实现这一点UICollectionViewController

UITableViewCell 中的滚动视图不会保存位置

更新1:

https://imgur.com/a/F8EGsTx

ViewController.swift

import UIKit

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = .white
        collectionView?.register(CategoryCell.self, forCellWithReuseIdentifier: cellId)
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CategoryCell
        cell.nameLabel.text = "Horizontal list #\(indexPath.item)"
        return cell
    }

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

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 150)
    }

}

CategoryCell.swift

import UIKit

class CategoryCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    let cellId = "categoryId"

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

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

    var nameLabel: UILabel = {
        let label = UILabel()
        label.text = "Horizontal list #1"
        label.font = UIFont.systemFont(ofSize: 16)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let appsCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = .white
        return collectionView
    }()

    let dividerLineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white: 0.4, alpha: 0.4)
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    func setupViews() {

        addSubview(appsCollectionView)
        addSubview(dividerLineView)
        addSubview(nameLabel)

        appsCollectionView.dataSource = self
        appsCollectionView.delegate = self

        appsCollectionView.register(AppCell.self, forCellWithReuseIdentifier: cellId)

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-14-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-14-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": dividerLineView]))

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": appsCollectionView]))

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[nameLabel(30)][v0][v1(0.5)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": appsCollectionView, "v1": dividerLineView, "nameLabel": nameLabel]))

    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! AppCell
        cell.imageView.backgroundColor = UIColor(hue: CGFloat(indexPath.item) / 20.0, saturation: 0.8, brightness: 0.9, alpha: 1)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: frame.height - 32)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0, 14, 0, 14)
    }

}

AppCell.swift

import UIKit

class AppCell: UICollectionViewCell {

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

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

    let imageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.layer.cornerRadius = 16
        iv.layer.masksToBounds = true
        return iv
    }()

    func setupViews() {
        addSubview(imageView)

        imageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.width)
    }
}

标签: iosswiftuicollectionviewuicollectionviewcellhorizontallist

解决方案


我终于明白了:)

感谢3年前的项目!来自伊凡隆

https://github.com/irfanlone/Collection-View-in-a-collection-view-cell

它也可以工作并支持界面方向,但需要一些优化。

例如,如果您向右滚动,然后快速向下滚动,然后再滚动回顶部,则单元格的右边缘有额外的边距!界面方向也有一些问题。

谁有完整版,请分享,谢谢。

对于任何可能感兴趣的人,在指定的文件中添加以下代码。

ViewController.swift

var storedOffsets = [Int: CGFloat]()

override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    guard let collectionViewCell = cell as? CategoryCell else { return }
    collectionViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
}

override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    guard let collectionViewCell = cell as? CategoryCell else { return }
    storedOffsets[indexPath.row] = collectionViewCell.collectionViewOffset
}

CategoryCell.swift

var collectionViewOffset: CGFloat {
    set {
        appsCollectionView.contentOffset.x = newValue
    }

    get {
        return appsCollectionView.contentOffset.x
    }
}

推荐阅读