Swift find superview of given class with generics

天大地大妈咪最大 提交于 2019-12-05 01:31:46

Swift 3/4

This is a more concise way:

extension UIView {

    func superview<T>(of type: T.Type) -> T? {
        return superview as? T ?? superview.compactMap { $0.superview(of: type) }
    }

    func subview<T>(of type: T.Type) -> T? {
        return subviews.compactMap { $0 as? T ?? $0.subview(of: type) }.first
    }

}

Usage:

let tableView = someView.superview(of: UITableView.self)
let tableView = someView.subview(of: UITableView.self)

No need to pass in the type of the class you want (at least in Swift 4.1)…

extension UIView {    
    func firstSubview<T: UIView>() -> T? {
        return subviews.compactMap { $0 as? T ?? $0.firstSubview() as? T }.first
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!