【问题标题】:UICollectionViewHeader - Calculate the size of a complex viewUICollectionViewHeader - 计算复杂视图的大小
【发布时间】:2019-07-05 21:22:19
【问题描述】:

我有一个 UICollectionReusableView,它有 2 个 UIView 作为子视图,它们本身有不同的视图(例如图像和标签)。这最能代表层次结构。

HeaderView(UICollectionReusableView)
    |-- UIView
           |-- Label
           |-- UIButton
           |-- UIButton
    |--UIView
           |-- UIImageView
           |-- UIStackview
                   |-- UILabel
                   |-- UILabel
           |-- UILabel
           |-- UILabel

现在,为了解决这个问题,我已经放弃了网络。但我能找到的只是计算UILabel 的高度。我真的需要知道我是如何计算的。我什至尝试在referenceSizeForHeaderInSection 中引用标题并调用layoutIfNeeded(),然后检查帧。但这似乎不起作用。

我真的很想对此进行解释以及如何实现这一目标的解决方案。

【问题讨论】:

    标签: ios swift uitableview uicollectionview


    【解决方案1】:

    您可以尝试在

    中计算 HeaderView 的大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    
    // if don't use xib file for HeaderView
    let header = HeaderView()
    
    // if use xib
    let bundle = Bundle(for: HeaderView.self)
    let nibName = String(describing: HeaderView.self)
    let nib = bundle.loadNibNamed(nibName, owner: HeaderView.self, options: nil)
    let header = nib?.first!
    
    // just setup your header with needed data
    header.setup(from: yourDataSource)
    
    // set hear needed width
    header.setup.frame.size.width = UIScreen.main.bounds.width
    
    header.setNeedsLayout()
    header.layoutIfNeeded()
    
    let size = header.systemLayoutSizeFitting(header.frame.size)
    
    return size
    }
    

    在标题设置方法中设置所有视图

    func setup(from data: YourDataSource){
       header.label1.text = data.name
       header.label2.text = data.info
       /// just setup all your field
       ....
    
    }
    

    【讨论】:

    • 感谢您的回复。你能解释一下设置部分吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多