0

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

4

1 回答 1

0

在这里,您实际上并不需要 variable deviceName: String。您可以直接将值设置为deviceNameLabel: NSTextField,如下所示:

cell.deviceNameLabel.stringValue = "Hello World"

如果您确实需要该变量,则可以尝试该didSet方法,如下所示:

public var deviceName:String = "Unknown Device Name" {
    didSet {
        cell.deviceNameLabel.stringValue = deviceName
    }
}
于 2020-06-04T08:57:08.013 回答