gpt4 book ai didi

swift - 扩展中的类函数转换为自身

转载 作者:行者123 更新时间:2023-11-30 10:12:07 25 4
gpt4 key购买 nike

我正在尝试创建一个用于加载 UIView 的扩展来自 XIB 的(和子类)。我们的愿望是让扩展返回UIView的特定子类。 。这是我到目前为止所得到的:

extension UIView {

class func instantiateNIB(name: String, bundle: NSBundle? = nil) -> UIView? {
let nib = UINib(nibName: name, bundle: bundle)
let views = nib.instantiateWithOwner(nil, options: nil)

for view in views {
if let match = view as? UIView {
return match
}
}

return nil
}

}

然后:

let spinner: Spinner = Spinner.instantiateNIB("Spinner") as! Spinner
let rater: Rater = Rater.instantiateNIB("Rater") as! Rater

问题是此方法始终返回 UIView这需要在后续调用中强制向下转换。是否可以修改它以自动执行向下转换?例如:

let spinner = Spinner.instantiateNIB(name: "Spinner")
let rater = Rater.instantiateNIB(name: "Rater")

最佳答案

试试这个:

extension UIView {

class func instantiateNIB(name: String, bundle: NSBundle? = nil) -> Self? {
return instantiateNIB(self, name: name, bundle: bundle)
}

private class func instantiateNIB<T>(type: T.Type, name: String, bundle: NSBundle? = nil) -> T? {
let nib = UINib(nibName: name, bundle: bundle)
let views = nib.instantiateWithOwner(nil, options: nil)

for view in views {
if let match = view as? T {
return match
}
}

return nil
}

}

关于swift - 扩展中的类函数转换为自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32389069/

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