我正在使用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!
}
Header
是NSCollectionViewItem
import Cocoa
class Header: NSCollectionViewItem {
var title: String!
...
//Write title value in a textField
...
}
我的问题是:如何设置viewForSupplementaryElementOfKind
的标题值?
我需要这样的东西:
答案 0 :(得分:2)
这里有点棘手,我希望Apple能够通过更好地利用NSCollectionViewItem
实际上,从示例代码CocoaSlideCollection
开始,显示带有可变文本的标题的方法是查看标题视图的子视图并获取对NSTextField
的引用,然后设置stringValue
。
与Swift一起行动:
HeaderView
,它是NSView的子类HeaderView
设置为标题笔尖视图在HeaderView
中,实现此变量titleTextField
lazy var titleTextField: NSTextField? = {
for view in self.subviews {
if view is NSTextField {
return view as? NSTextField
}
}
return nil
}()
在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。