带有页眉和页脚的 NSCollectionView

Gee*_*k20 4 macos cocoa nscollectionview swift xcode7

我需要这样的东西:

在此处输入图片说明

但我的代码是这样做的:

在此处输入图片说明

func collectionView(collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> NSView {
    let a = myView()
    if kind == NSCollectionElementKindSectionHeader {
        a.frame = NSMakeRect(0, 0, 1000, 10)
    }
    else if kind == NSCollectionElementKindSectionFooter {
        a.frame = NSMakeRect(0, 0, 1000, 12)
    }
    return a
}

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

override func numberOfItemsInSection(section: Int) -> Int {
    if section == 0 {
        return 5
    }
    else if section == 1 {
        return 5
    }
    return 10
}
Run Code Online (Sandbox Code Playgroud)

两个页眉和页脚位于 x=0,y=0 位置,那么如何从我的自定义视图(页眉和页脚)计算y位置?

Har*_* Ng 6

根据 Apple 的示例项目CocoaSlideCollection,节页眉和页脚可用于NSCollectionViewFlowLayout、查看AAPLBrowserWindowControllerAAPLWrappedLayout了解更多详细信息。

转换成 Swift 和英文 :P,简要说明如下:

  1. 实现协议 NSCollectionViewDelegateFlowLayout
  2. 实现这两个方法referenceSizeForHeaderInSectionreferenceSizeForFooterInSection
  3. viewForSupplementaryElementOfKind 将在第 2 步之后调用

对于第 3 步,我使用以下代码

func collectionView(collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> NSView {
    var nibName: String?
    if kind == NSCollectionElementKindSectionHeader {
        nibName = "Header"
    } else if kind == NSCollectionElementKindSectionFooter {
        nibName = "Footer"
    }
    let view = collectionView.makeSupplementaryViewOfKind(kind, withIdentifier: nibName!, forIndexPath: indexPath)
    return view
}
Run Code Online (Sandbox Code Playgroud)

该标识nibName用在这里,链接到两个笔尖文件我创建设置的NSView,即Header.xibFooter.xib

这是我得到的结果 collectionView。

带有页眉和页脚的 NSCollectionView

希望它有所帮助,我正在为此创建一个视频教程。帮助它有帮助。

编辑1:

示例代码现已可用