简体   繁体   English

如何在 Swift for macOS 中迭代子视图并返回 object 类型

[英]How to iterate through subviews in Swift for macOS and return object types

After finding this question and answers , I thought I would try to reduce the size of my code considerably by looping through various objects in the view and set parameters.找到这个问题和答案后,我想我会尝试通过遍历视图中的各种对象并设置参数来大大减少代码的大小。

I cannot use the tag value because I do not set tags, except in rare circumstances.我不能使用标签值,因为我没有设置标签,除非在极少数情况下。 I set plain language identifiers for all of my UI elements.我为我的所有 UI 元素设置了简单的语言标识符。 I will use NSTextField as an example to try and set the delegate for each NSTextField in the view.我将使用 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
            }
        }
    }
}

I am being told that Value of type 'NSView' has no member 'delegate' , which makes sense because the NSView of the NSTextField is what is actually being placed into the list, not the actual NSTextField object.我被告知Value of type 'NSView' has no member 'delegate' ,这是有道理的,因为 NSTextField 的 NSView 是实际放入列表中的内容,而不是实际的 NSTextField object。

Since IBOutlet Collections aren't available for macOS, I can't simply iterate through a collection to do what I want to do.由于 IBOutlet Collections 不适用于 macOS,我不能简单地遍历集合来做我想做的事。 At least as a far as I know of.至少据我所知。

I assume the goal is to get textFields to have type [NSTextField].我假设目标是让textFields具有 [NSTextField] 类型。

Right now, you have filter with is (which doesn't change type)现在,你有filter is (它不会改变类型)

let textFields = self.view.subviews.filter { $0.isKind(of: NSTextField.self) }

You should change this to compactMap with as?您应该将其更改为compactMap with as? (which does change type). (这确实改变了类型)。

let textFields = self.view.subviews.compactMap { $0 as? NSTextField }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM