使用 NSCollectionView 设置 Header 标题

Set Header title with NSCollectionView

我正在使用 NSCollectionView,CollectionView 有 headers。我需要为每个 header.

设置一个特定的标题

我的代码:

func collectionView(collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> NSView {
        var view: NSView?
        if kind == NSCollectionElementKindSectionHeader {
            view = collectionView.makeSupplementaryViewOfKind(kind, withIdentifier: "Header", forIndexPath: indexPath)
        }
        ...
        return view!
    }

Header 是一个 NSCollectionViewItem

import Cocoa

class Header: NSCollectionViewItem {

    var title: String!
    ...
    //Write title value in a textField
    ...
}

我的问题是:如何从 viewForSupplementaryElementOfKind 设置 title 值?

我需要这样的东西:

这里有点棘手,希望Apple能尽快改进API,更好地利用NSCollectionViewItem

事实上,从示例代码 CocoaSlideCollection 来看,显示带有可变文本的标题的方法是查看 Header 视图的子视图并获取对 NSTextField,然后设置 stringValue.

与Swift一起行动:

  1. 创建一个 HeaderView 它是 NSView
  2. 的子类
  3. HeaderView 设置为 Header 笔尖的视图
  4. HeaderView中实现这个变量titleTextField

    lazy var titleTextField: NSTextField? = {
        for view in self.subviews {
            if view is NSTextField {
                return view as? NSTextField
            }
        }
        return nil
    }()
    
  5. viewForSupplementaryElementOfKind 委托方法中,执行此操作

    let view = collectionView.makeSupplementaryViewOfKind(kind, withIdentifier: nibName!, forIndexPath: indexPath)
    if let view = view as? HeaderView {
        view.titleTextField?.stringValue = "Header Custom Value"
    }
    return view
    

我是这样使用的:

func collectionView(collectionView: CollectionView,viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> CollectionHeaderView!
{
    switch kind
    {
        case NSCollectionElementKindSectionHeader:  let contactsCollectionHeaderView                            = collectionView.makeSupplementaryViewOfKind(kind,withIdentifier:"ContactsCollectionHeader",forIndexPath:indexPath) as! ContactsCollectionHeaderView
                                                    contactsCollectionHeaderView.titleTextField?.stringValue    = self.collectionView(collectionView, titleForHeaderInSection:indexPath.section) ?? ""
                                                    return contactsCollectionHeaderView

        case "NSCollectionElementKindSelectionRectIndicator": return nil

        default:                                    return nil
    }

请注意,目前委托的方法签名是错误的,returned 视图在现实中是可选的,否则您无法return 像上面的 recindicator 这样的特殊定义类型。