Eilon
Eilon

Reputation: 2982

Finding a view of certain type within a parent

I use to find specific views within a parent usually like:

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

I would like to create a function that would take a type or an object of a certain type and return a view within the parent's subviews that corresponds with the type. Something along the lines of:

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()>) { ... }

But I can't figure out how to do it, I tried looking up the topic, but I'm afraid my knowledge of Swift is limiting me on this one.
How can I achieve this?

Upvotes: 0

Views: 360

Answers (1)

May Rest in Peace
May Rest in Peace

Reputation: 2207

You can create an extension like this :

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

Now you can use it like view.findView(byType: UIButton.self)

As @LeoDabus pointed out, a better extension would be :

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

Upvotes: 1

Related Questions