gpt4 book ai didi

ios - 在父级中查找某种类型的 View

转载 作者:行者123 更新时间:2023-11-29 05:29:47 25 4
gpt4 key购买 nike

我常常在 parent 中寻找特定的观点,通常如下:

let label: UILabel? = view.subviews.filter {$0 is UILabel}.first

我想创建一个函数,该函数将采用某种类型或某种类型的对象,并返回父级 subview 中与该类型相对应的 View 。大致如下:

extension UIView {
func findView(byType type: <Some Type or UIView object?>() -> UIView? {
return self.subviews.filter {$0 is <The type>}.first
}
}

// Usage
if let myLabel = view.findView(byType: <*UILabel.Type* or UILabel()>) { ... }

但我不知道该怎么做,我尝试查找主题,但我担心我对 Swift 的了解限制了我在这个主题上的能力。
我怎样才能做到这一点?

最佳答案

您可以创建这样的扩展:

extension UIView {
func findView<T>(byType type: T.Type) -> T? {
return self.subviews.filter {$0 is T}.first as? T
}
}

现在你可以像view.findView(byType: UIButton.self)那样使用它

正如 @LeoDabus 指出的,更好的扩展是:

func findView<T>(byType type: T.Type) -> T? {
return subviews.first { $0 is T } as? T
}

关于ios - 在父级中查找某种类型的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com