ios - 基于 UILabel 的动态 UICollectionView header 大小

标签 ios ios7 swift uicollectionview

我读过很多关于向 UICollectionView 添加 header 的帖子。在 Swift 的 iOS 7+ 应用程序中,我试图添加一个带有 UILabel 的 header ,其高度应根据 UILabel 的高度进行调整。 UILabel 的行数 = 0。

我已经在 IB 中使用 AutoLayout 设置了页眉

enter image description here

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

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
}

文本的显示似乎有效,但高度计算似乎无效(见下面的屏幕截图)。此外,我认为我也无法通过 collectionView...referenceSizeForHeaderInSection 函数访问 UILabel。关于如何正确计算 CGSize 有什么建议吗?

enter image description here

最佳答案

我是这样做的:

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."]

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

我的 UICollectionReusableView 子类 (MyHeaderCollectionReusableView) 中有一个名为 label 的标签 socket ,我通过分配它来将其用于我的节标题 View 在 Storyboard中(将“MyHeader”设置为剖面 View 的重用标识符)。提到的标签对部分标题边框具有水平和垂直空间限制,以便正确自动布局。

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)
    }

关于ios - 基于 UILabel 的动态 UICollectionView header 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25642493/

相关文章:

iOS Simulator 无法运行并且 xCode 构建应用程序的速度太慢

ios - Restkit删除特定对象的coredata中的所有对象

ios - Xcode 7 - 垂直间距约束

ios - AFNetworking 可以处理请求队列吗?

ios - AVQueuePlayer AVPlayerItemDidPlayToEndTimeNotification 调用失败

Swift - 如何管理转单管理?

html - 在 html 内容中添加字符串

swift - deinit 在 vi​​ewDidLoad 之前执行

iphone - iPhone 的横向模式下不显示 PayPal View

iphone - IOS模式segue返回黑屏