ios - 从 collectionView 返回什么(_ :viewForSupplementaryElementOfKind:at:) when you want to return nothing?

标签 ios swift uicollectionview

我有一个 UICollectionView,它有部分标题,但没有部分页脚。因此,我没有定义的页脚 View 。 Apple's documentation声明 您不得从此方法返回 nil。

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    switch kind {
    case UICollectionElementKindSectionHeader:
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
                                                                         withReuseIdentifier: "MyHeaderView",
                                                                         for: indexPath) as! MyHeaderView
        switch indexPath.section
        {
        case 0:
            headerView.label_title.text = "SOME HEADER"
        case 1:
            headerView.label_title.text = "ANOTHER HEADER"
        default:
            headerView.label_title.text = "UNKNOWN HEADER"
        }
        return headerView
    default:
        assert(false, "Unexpected element kind") // Not a good idea either
    }
    return nil // NOPE, not allowed
}

最佳答案

以上都不适合我。在我的例子中,我在同一个 View Controller 中有两个 UICollectionView 对象。首先是水平的,选择一个显示下面的 UICollectionView 的项目,它是垂直的并且包含部分标题。

来自 Apple docs :

This method must always return a valid view object. If you do not want a supplementary view in a particular case, your layout object should not create the attributes for that view. Alternatively, you can hide views by setting the isHidden property of the corresponding attributes to true or set the alpha property of the attributes to 0. To hide header and footer views in a flow layout, you can also set the width and height of those views to 0.

所以像往常一样将 headerView 出队,因为如果你不这样做,只返回一个 UICollectionReusableView() 的实例,Xcode 会提示标题 View 没有出队。然后,如果您出于某种原因不想显示它(对我来说,直到用户从上方的水平 Collection View 中选择一个项目)- 将 headerView 的宽度和高度设置为 0.0 并返回它。

let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: collectionHeaderReuseIdentifier, for: indexPath) 
if objects.isEmpty {
    headerView.frame.size.height = 0.0
    headerView.frame.size.width = 0.0
    return headerView
}
// Configure the header view here if needed
return headerView

关于ios - 从 collectionView 返回什么(_ :viewForSupplementaryElementOfKind:at:) when you want to return nothing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44843008/

相关文章:

ios - mach_wait_until() iPad 上的奇怪行为

ios - 在另一个 collectionview 的 header 中实现 collectionview 时出错

ios - 计算tableView的heightForRowAtIndexPath中的UICollectionView contentSize

iphone - 在 iOS 上以编程方式获取列表 Internet 访问点

ios - Swift 如何解决发送到实例 0x7fa9e0d8b7c0 的无法识别的选择器

swift - Firebase 和使用 Swift 读取嵌套数据

ios - 如何用内容填充分组的动态表格 View 单元格(swift)

ios - CollectionView referenceSizeForHeaderInSection 是应用程序崩溃的原因

ios - Xcode 5.1 - 没有可编译的架构(ONLY_ACTIVE_ARCH=YES,active arch=x86_64,VALID_ARCHS=i386)

ios - Swift 设置 View 是如何实现的