UICollectionView具有另一个UIView内的动态高度

时间:2017-06-23 19:54:44

标签: ios swift uicollectionview

我有一个UICollectionView组件作为UIViewController中的一个块,它将在构建约束之后和获取数据之后动态地改变它的高度。我应该在哪里找出解决方案。

如何实现this组件并在获取后自动调整它。

ParamsTable类,其字段为UICollectionView类型:

class ParamsTable: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    lazy var collectionView: UICollectionView = {/*...*/}()        

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

            collectionView.register(ParamCell.self, forCellWithReuseIdentifier: cellId)

            addSubview(collectionView)
            addConstrainsWithFormat(format: "H:|[v0]|", views: collectionView)
            addConstrainsWithFormat(format: "V:|[v0]|", views: collectionView)
        }
        /*...*/
}

在另一个UIView组件中有一个ParamsTable实例的AdPage类:

class AdPage: UIViewController, UICollectionViewDelegateFlowLayout {

/*...*/

let stackView: UIStackView = {
    /*...*/
}()

let paramsTable: ParamsTable = {
    let table = ParamsTable()
    return table
}()

override func viewDidLoad() {
    super.viewDidLoad()

    fetch()

    setupViewHierarchy()
}

func setupViewHierarchy() {
    /*...*/

    view.addConstrainsWithFormat(format: "H:|[v0]", views: stackView)
    view.addConstrainsWithFormat(format: "V:|-16-[v0]|", views: stackView)

    // calculate a 'new' height after fetching
    stackView.addConstrainsWithFormat(format:"V:[v0(\(paramsTable.params.count * 16))]", views: paramsTable)
    stackView.addConstrainsWithFormat(format: "H:|[v0]|", views: paramsTable)
}

extension UIView {

    func addConstrainsWithFormat(format: String, views: UIView...) {
        var viewsDictionary = [String: UIView]()
        for (index, view) in views.enumerated() {
            let key = "v\(index)"
            viewsDictionary[key] = view
            view.translatesAutoresizingMaskIntoConstraints = false
        }

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
    }
}

0 个答案:

没有答案