使用NSCollectionView设置标题标题

时间:2016-01-15 00:52:01

标签: swift macos cocoa xcode7 nscollectionview

我正在使用NSCollectionView,CollectionView有标题。我需要为每个标题设置一个特定的标题。

我的代码:

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

HeaderNSCollectionViewItem

import Cocoa

class Header: NSCollectionViewItem {

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

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

我需要这样的东西:

enter image description here

2 个答案:

答案 0 :(得分:2)

这里有点棘手,我希望Apple能够通过更好地利用NSCollectionViewItem

来尽快改进其API

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

与Swift一起行动:

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

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

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

答案 1 :(得分:1)

我这样用:

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
    }

请注意,目前委托的方法签名是错误的,返回的视图实际上是可选的,否则您无法返回特殊的defind类,如上面的rectindicator。