我正在尝试从父 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 方面有过一些经验,但不记得有这个问题。