在找到這個問題和答案之后,我想我會嘗試通過回圈視圖中的各種物件并設定引數來顯著減小代碼的大小。
我不能使用標簽值,因為我沒有設定標簽,除非在極少數情況下。我為我的所有 UI 元素設定了簡單的語言識別符號。我將以 NSTextField 為例,嘗試為視圖中的每個 NSTextField 設定委托。
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate {
@IBOutlet var myTextField1: NSTextField!
// ... and many, many more NSTextFields ...
override func viewDidLoad {
super.viewDidLoad()
let textFields = self.view.subviews.filter { $0.isKind(of: NSTextField.self) }
for textField in textFields {
if textField.identifier!.rawValue[textField.identifier!.rawValue.startIndex] != "_" { // Avoiding Swift assigned identifiers
textField.delegate = self
}
}
}
}
有人告訴我Value of type 'NSView' has no member 'delegate'
,這是有道理的,因為 NSTextField 的 NSView 是實際放入串列的內容,而不是實際的 NSTextField 物件。
由于 IBOutlet 集合不適用于 macOS,我不能簡單地遍歷集合來做我想做的事情。至少據我所知。
uj5u.com熱心網友回復:
我假設目標是獲得textFields
型別 [NSTextField]。
現在,你有filter
with is
(不會改變型別)
let textFields = self.view.subviews.filter { $0.isKind(of: NSTextField.self) }
您應該將其更改為compactMap
with as?
(確實會更改型別)。
let textFields = self.view.subviews.compactMap { $0 as? NSTextField }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448192.html