带页眉和页脚的NSCollectionView

时间:2016-01-13 04:16:35

标签: swift macos cocoa xcode7 nscollectionview

我需要这样的东西:

enter image description here

但我的代码是这样做的:

enter image description here

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
}

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

2 个答案:

答案 0 :(得分:4)

根据Apple的示例项目CocoaSlideCollection,部分页眉和页脚可供NSCollectionViewFlowLayout使用,请查看AAPLBrowserWindowControllerAAPLWrappedLayout了解详情。

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

  1. 实施协议NSCollectionViewDelegateFlowLayout
  2. 实施两种方法referenceSizeForHeaderInSectionreferenceSizeForFooterInSection
  3. viewForSupplementaryElementOfKind将在第2步之后调用
  4. 对于第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
    }
    

    此处使用的标识符nibName,链接到我为设置NSView而创建的两个nib文件,即Header.xibFooter.xib

    这是我得到的结果collectionView。

    NSCollectionView with Header and Footer

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

    编辑1:

    Sample Code现已推出

答案 1 :(得分:0)

我猜你应该检查两件事

首先点击集合视图属性检查器

你可以看到像这样的复选框

配件*部分页眉,部分页脚

其次是覆盖关键字

我猜你应该在你的func关键字前放置override关键字!

相关问题