ios - 如何仅对内容单元格而不是 UICollectionView 中的标题应用不同的 contentInset

标签 ios swift uicollectionview uicollectionviewlayout

我使用 insetForSectionAtIndex 方法为我的 Collection View 中的一个部分设置 contentInset,我不想将该插图应用于该部分的标题。我需要标题宽度与屏幕一样宽。

内容插入

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

标题

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
}

最佳答案

我只需要在我的一个项目中做同样的事情。

我应用的解决方案:

在 Storyboard 中,我的 Collection View 占据了具有自动布局约束的全屏。

在viewDidLoad中:

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

我将 collectionView 委托(delegate)设置为 self 并且也符合

UICollectionViewDelegateFlowLayout 协议(protocol)。

然后您可以访问您在我返回另一个 UIEdgeInsets 时使用的方法

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

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

    }

它对我有用。

看看最后的样子。

enter image description here

希望这能够帮助到其他人。

关于ios - 如何仅对内容单元格而不是 UICollectionView 中的标题应用不同的 contentInset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38474482/

相关文章:

ios - UICollectionCellView - 带来重复的图像

ios - 增加、更新和保存所有单元格 UICollectionView 中的分数

ios - 如何在后台使用 session.uploadTask 我正在崩溃

ios - 如何将 UITapGestureRecognizer 添加到 TableView 单元格内的 UILabel?

iOS Swift Panframe 框架有声音但没有视频

ios - 如何更改按钮上的操作目标 - Swift

ios - 将代码从 obj-c 转换为 Swift 的问题

ios - 找不到导入的文件

ios - UIView 作为@EnvironmentObject 的订阅者

ios - 带有 iOS 应用程序图像查看器的 ImageSlider