基于UILabel的动态UICollectionView标头大小

Dea*_*ean 26 ios uicollectionview ios7 swift

我已经阅读了一些关于向UICollectionView添加标题的帖子.在Swift的iOS 7+应用程序中,我正在尝试添加一个带有UILabel的标头,其高度应根据UILabel的高度进行调整.UILabel的行= 0.

我已经使用AutoLayout在IB中设置了标题

在此输入图像描述

ViewController实现UICollectionViewDelegate, UICollectionViewDataSource.我没有为标题设置自定义类,但我正在使用这两个函数:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
      //description is a String variable defined in the class
    let size:CGSize = (description as NSString).boundingRectWithSize(CGSizeMake(CGRectGetWidth(collectionView.bounds) - 20.0, 180.0), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 16.0)], context: nil).size
    return CGSizeMake(CGRectGetWidth(collectionView.bounds), ceil(size.height))
}

func collectionView(collectionView: UICollectionView!, viewForSupplementaryElementOfKind kind: String!, atIndexPath indexPath: NSIndexPath!) -> UICollectionReusableView! {
    var reusableview:UICollectionReusableView = UICollectionReusableView()
    if (kind == UICollectionElementKindSectionHeader) {
                    //listCollectionView is an @IBOutlet UICollectionView defined at class level, using collectionView crashes
            reusableview = listCollectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "ListHeader", forIndexPath: indexPath) as UICollectionReusableView
            let label = reusableview.viewWithTag(200) as UILabel  //the UILabel within the header is tagged with 200
            label.text = description   //description is a String variable defined in the class
        }
    }
    return reusableview
}
Run Code Online (Sandbox Code Playgroud)

显示文本似乎有效,但高度计算似乎不起作用(见下面的截图).另外,我认为我也不能通过该collectionView...referenceSizeForHeaderInSection功能访问UILabel .有关如何正确计算CGSize的任何建议?

在此输入图像描述

Alv*_*aro 25

我就这样做了:

let labels = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ac lorem enim. Curabitur rhoncus efficitur quam, et pretium ipsum. Nam eu magna at velit sollicitudin fringilla nec nec nisi. Quisque nec enim et ipsum feugiat pretium. Vestibulum hendrerit arcu ut ipsum gravida, ut tincidunt justo pellentesque. Etiam lacus ligula, aliquet at lorem vel, ullamcorper commodo turpis. Nullam commodo sollicitudin mauris eu faucibus.",
"Lorem ipsum dolor",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ac lorem enim. Curabitur rhoncus efficitur quam, et pretium ipsum. Nam eu magna at velit sollicitudin fringilla nec nec nisi. Quisque nec enim et ipsum feugiat pretium."]
Run Code Online (Sandbox Code Playgroud)

基本思想是创建与UILabel将在节头中显示的节点相同的节点.该标签将用于为referenceSizeForHeaderInSection方法中的标题设置所需的大小.

我有一个label在我的UICollectionReusableView子类(MyHeaderCollectionReusableView)中调用的标签出口,我通过在故事板中指定它来将其用于我的节标题视图(将"MyHeader"设置为剖面视图的重用标识符).提到的标签对部分标题边框具有水平和垂直空间限制,以便正确地自动布局.

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 3
    }

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

        let headerView =
        collectionView.dequeueReusableSupplementaryViewOfKind(kind,
            withReuseIdentifier: "MyHeader",
            forIndexPath: indexPath)
            as MyHeaderCollectionReusableView

        headerView.label.text = labels[indexPath.section]

        return headerView

    }

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        // that -16 is because I have 8px for left and right spacing constraints for the label.
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, collectionView.frame.width - 16, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
       //here, be sure you set the font type and size that matches the one set in the storyboard label
        label.font = UIFont(name: "Helvetica", size: 17.0)
        label.text = labels[section]
        label.sizeToFit()

// Set some extra pixels for height due to the margins of the header section.  
//This value should be the sum of the vertical spacing you set in the autolayout constraints for the label. + 16 worked for me as I have 8px for top and bottom constraints.
        return CGSize(width: collectionView.frame.width, height: label.frame.height + 16)
    }
Run Code Online (Sandbox Code Playgroud)

  • 这真的是最干净的解决方案吗?为什么苹果?为什么? (64认同)
  • 有声有色 (2认同)

Nic*_*ger 5

就像提问者一样,我有一个UICollectionView,其中包含一个带有单个标签的标题,我希望它的高度可以变化.我创建了一个扩展来UILabel测量具有已知宽度的多线标签的高度:

public extension UILabel {
    public class func size(withText text: String, forWidth width: CGFloat) -> CGSize {
        let measurementLabel = UILabel()
        measurementLabel.text = text
        measurementLabel.numberOfLines = 0
        measurementLabel.lineBreakMode = .byWordWrapping
        measurementLabel.translatesAutoresizingMaskIntoConstraints = false
        measurementLabel.widthAnchor.constraint(equalToConstant: width).isActive = true
        let size = measurementLabel.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
        return size
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:以上是Swift 3语法.

然后我实现了如下的头大小方法UICollectionViewDelegateFlowLayout:

extension MyCollectionViewController : UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let text = textForHeader(inSection: section)
        var size =  UILabel.size(withAttributedText: text, forWidth: collectionView.frame.size.width)
        size.height = size.height + 16
        return size
    }
}
Run Code Online (Sandbox Code Playgroud)

计算标题大小的工作委托给上面的UILabel 扩展名.这+16是一个实验得出的固定偏移量(8 + 8),它基于边距,可以通过编程方式获得.

标头回调中所需的只是设置文本:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    if kind == UICollectionElementKindSectionHeader, let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as?  MyCollectionHeader {
        let text = textForHeader(inSection: section)
        headerView.label.text = text
        return headerView
    }
    return UICollectionReusableView()
}
Run Code Online (Sandbox Code Playgroud)


Mun*_*ndi -1

你必须实现该UICollectionViewDelegate方法referenceSizeForHeaderInSection

boundingRectWithSize:options:context:在那里,您必须通过调用具有适当属性的字符串来计算高度,而不使用标签。