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

时间:2015-09-04 02:13:33

标签: swift

我试图创建一个从XIB加载UIView(和子类)的扩展。希望扩展返回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")

1 个答案:

答案 0 :(得分:1)

试试这个:

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
    }

}