gpt4 book ai didi

swift - 从 Swift 函数获取通用类型 UIView

转载 作者:行者123 更新时间:2023-11-28 13:25:33 24 4
gpt4 key购买 nike

我正在尝试创建一个函数,通过给定一个 UIView,它递归地迭代所有 subview ,直到找到 T 类型的 UIView。到目前为止,我有:

func getType(from view: UIView) -> AdaptiveContainerView? {

for aView in view.subviews {
if let adapView = aView as? AdaptiveContainerView {
return adapView
}
else {
return getType(from: aView)
}
}

return nil

}

现在我正在尝试折射该函数,以便它获取 UIView 类型并在找到时返回它。通过 UIView 类型我的意思是:

class MyView: UIView {}

我的第一个方法是

func getGenericType<T, Q:UIView>(from view: UIView, ofType: T) -> Q? {

for aView in view.subviews {
if aView is ofType {

}
...
}

return nil

}

但是我遇到了以下错误:

Use of undeclared type 'ofType'

有什么想法吗?

谢谢

最佳答案

对于静态

func getGenericType<Q:MyView>(from view: UIView) -> Q? {

for aView in view.subviews {

if let res = aView as? Q {

return res
}
else {

return getGenericType(from: aView)
}

}

return nil
}

打电话

let res = getGenericType(from: self.view) // res of type MyView 

如果需要动态发送参数

func getGenericType<T:UIView>(from view: UIView,type:T.Type) -> T? {

for aView in view.subviews {

if let res = aView as? T {

return res
}
else {

return getGenericType(from: aView,type:T.self)
}

}

return nil
}

打电话

let res = getGenericType(from: self.view,type:MyView.self)  // res of type MyView 

关于swift - 从 Swift 函数获取通用类型 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416264/

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