我正在尝试从父NSCollectionViewDataSource更新NSCollectionViewItem内部的NSTextField标题。这是我的代码。
NSCollectionViewDataSource
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let cell = collectionView.makeItem(
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "MacDeviceItem"),
for: indexPath
) as! MacDeviceItem
let device = devicesList[indexPath.item]
cell.deviceName = "Hello World"
return cell
}
NSCollectionViewItem
class MacDeviceItem: NSCollectionViewItem {
dynamic public var deviceName:String = "Unknown Device Name"
@IBOutlet weak var deviceImage: NSImageView!
@IBOutlet weak var deviceNameLabel: NSTextField!
@IBOutlet weak var deviceStatusLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
updateSelection()
}
override func viewDidLayout() {
super.viewDidLayout()
view.layer?.cornerRadius = 7
print(deviceName)
}
override func viewDidAppear() {
self.deviceNameLabel?.stringValue = deviceName
}
private var selectionColor : CGColor {
let selectionColor : NSColor = (isSelected ? .controlAccentColor : .clear)
return selectionColor.cgColor
}
private var selectionTextColor : NSColor {
let selectionTextColor : NSColor = (isSelected ? .selectedMenuItemTextColor : .controlTextColor)
return selectionTextColor
}
override var isSelected: Bool {
didSet {
super.isSelected = isSelected
updateSelection()
// Do other stuff if needed
}
}
override func prepareForReuse() {
super.prepareForReuse()
updateSelection()
}
private func updateSelection() {
view.layer?.backgroundColor = self.selectionColor
deviceNameLabel?.textColor = self.selectionTextColor
deviceStatusLabel?.textColor = self.selectionTextColor
}
}
如果我在viewDidLoad上打印deviceName的值,则该值在那里。但是,当尝试在ViewDidAppear中设置标签时,什么也没有发生,并且该变量已重置为默认值。我对Swift还是很陌生,但是以前有一些Objective-C的经验,但是不记得有这个问题。
这里您实际上不需要变量deviceName: String
。您可以将值直接设置为deviceNameLabel: NSTextField
,如下所示:
cell.deviceNameLabel.stringValue = "Hello World"
如果您实际上需要变量,则可以尝试didSet
方法,如下所示:
public var deviceName:String = "Unknown Device Name" {
didSet {
cell.deviceNameLabel.stringValue = deviceName
}
}