簡體   English   中英

macOS:將Swift屬性暴露給Cocoa Bindings的正確方法

[英]macOS: Correct way of exposing Swift properties to Cocoa Bindings

我正在研究Mac上現有的Swift / Objective-C項目,我在代碼中創建了一些UI。 我根據我在使用NSArrayController管理的NSTableView中的選擇啟用了一個按鈕(原因)。

我在MyController上有一個屬性selectionIndexes

@objc var selectionIndexes : IndexSet = IndexSet()

我不確定是否有必要使@objc對Cocoa Bindings系統可見。

我使用以下命令連接按鈕的enabled綁定:

newButton.bind(NSBindingName.enabled, to: MyController.sharedInstance,
     withKeyPath: "selectionIndexes", 
     options: [NSBindingOption.valueTransformer : MyTransformer()])

這樣工作正常,使用正確的屬性調用轉換器並且啟用設置正確, 但是對選擇的更改不會觸發綁定 ,因此按鈕保持禁用狀態。

我必須明確告訴系統我正在改變值,例如

self.willChangeValue(for: \.selectionIndexes )
self.selectionIndexes = proposedSelectionIndexes
self.didChangeValue(for: \.selectionIndexes)

這看起來很蹩腳。 有沒有更好的方法呢?

@objc是將屬性公開給Objective-C運行時所必需的。

要使屬性鍵值觀察符合,您必須添加dynamic關鍵字

@objc dynamic var selectionIndexes = IndexSet()

並刪除...ChangeValue(for

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM