简体   繁体   English

如何为内容单元格应用不同的contentInset,但不为UICollectionView中的标题应用

[英]How to apply different contentInset only for contents cells but not for a header in UICollectionView

I use insetForSectionAtIndex method to set contentInset for a section in my collection view and I don't want to apply that inset to a header of the section. 我使用insetForSectionAtIndex方法为我的集合视图中的一个部分设置contentInset,我不想将该插入应用于该部分的标题。 I need the header width to be as wide as the screen. 我需要标题宽度与屏幕一样宽。

ConentInset ConentInset

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    if section == 1 {
        return UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
    }

    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

Header

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

    let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: opsMainDescriptionSegmentedControlCellId, forIndexPath: indexPath) as! MyHeader

    return header
}

I just had to do this exact same thing in one of my project. 我只需要在我的一个项目中做同样的事情。

The solution I applied: 我申请的解决方案:

In Storyboard, my collection view takes up the full screen with Auto-Layout constraints. 在Storyboard中,我的集合视图占据了自动布局约束的全屏。

In viewDidLoad: 在viewDidLoad中:

collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

I set the collectionView delegate to self and also conform to the 我将collectionView委托设置为self并且也符合

UICollectionViewDelegateFlowLayout protocol. UICollectionViewDelegateFlowLayout协议。

You then have access to the method you've used where I return another UIEdgeInsets 然后,您可以访问我在返回另一个UIEdgeInsets时使用的方法

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        return UIEdgeInsets(top: 15, left: 20, bottom: 15, right: 20)

    }

and it worked for me. 它对我有用。

See how it looked in the end. 看看它到底是怎么回事。

在此输入图像描述

Hope this will be able to help others. 希望这能够帮助别人。

You cannot do this. 你不能做这个。 UICollectionViews headers need to be as wide as the UICollectionView itself. UICollectionViews标头需要与UICollectionView本身一样宽。 If you want the header to be shorter (width) than the UICollectionView - my suggestion is to use a separate UIView inside the header and set the header to clear. 如果您希望标题比UICollectionView更短(宽度) - 我的建议是在标题内使用单独的UIView并将标题设置为清除。 That way it will appear that its shorter than the width of the UICollectionView . 这样它看起来会比UICollectionView的宽度短。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM