ios – UICollectionView AutoSize标题高度

我正在为iOS 8编码.

我有一个UICollectionReusableView,它被用作UICollectionView的头

class UserHeader: UICollectionReusableView {
...
}

我的视图集合做了一些事情:

在viewDidLoad中加载NIB

override func viewDidLoad() {
super.viewDidLoad()
resultsCollectionView.registerNib(UINib(nibName: "UserHeader",bundle: nil),forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,withReuseIdentifier: "UserHeader")
}

在referenceSizeforHeaderInSection中设置标题高度.

func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,referenceSizeforHeaderInSection section: Int) -> CGSize {
    return CGSizeMake(0,500)
}

但是,我的UserHeader视图包含许多在运行时高度变化的UILabel,UIViews,如何为referenceSizeforHeaderInSection指定动态的高度?或者,如果我不想在iOS 8中使用referenceSizeforHeaderInSection进行自动调整大小,请告诉我应该使用的内容.提前致谢.

为了完整起见,这是我加载视图的方式,但我不确定这是否与此讨论相关:

func collectionView(collectionView: UICollectionView!,viewForSupplementaryElementOfKind kind: String!,atIndexPath indexPath: NSIndexPath!) -> UICollectionReusableView! {
    var reusableview:UICollectionReusableView = UICollectionReusableView()
    if (kind == UICollectionElementKindSectionHeader) {
        let userHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader,withReuseIdentifier: "UserHeader",forIndexPath: indexPath) as! UserHeader

                    ... extra code to modify UserHeader

                    reusableview = userHeaderView
    }
    return reusableview
}

解决方法

我遇到了类似的问题并通过在视图中使用NSLayoutConstraints来修复它,以指定标题视图的高度.在视图控制器中,我然后配置集合视图的标题
fileprivate var expectedSectionHeaderFrame = CGRect.zero
let headerIdentifier = "HeaderView"

func calculateHeaderFrame() -> CGRect {
    headerView.setNeedsLayout()
    headerView.layoutIfNeeded()

    let expectedHeaderSize = CGSize(width: view.bounds.width,height: headerView.systemLayoutSizefitting(UILayoutFittingCompressedSize).height)

    return CGRect(origin: .zero,size: expectedHeaderSize)
}

func collectionView(_ collectionView: UICollectionView,referenceSizeforHeaderInSection section: Int) -> CGSize {
    expectedSectionHeaderFrame = calculateHeaderFrame()
    return expectedSectionHeaderFrame.size
}

func collectionView(_ collectionView: UICollectionView,viewForSupplementaryElementOfKind kind: String,at indexPath: IndexPath) -> UICollectionReusableView {
    guard kind == UICollectionElementKindSectionHeader else { fatalError("Unexpected kind of supplementary view in (type(of: self))") }

    let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,withReuseIdentifier: headerIdentifier,for: indexPath)
    headerView.frame = expectedSectionHeaderFrame

    return headerView
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...