Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the kind of subview object the view is containing in it?

I am trying to find a specific class object added as Subview to a UIView, but I could not find anything.

like image 977
Dipti Y W Avatar asked Jun 26 '13 12:06

Dipti Y W


3 Answers

for(UIView *aView in yourView.subviews){
    if([aView isKindOfClass:[YourClass class]]){
       //YourClass found!!
    }
}
like image 120
Ishank Avatar answered Oct 01 '22 17:10

Ishank


for example if you are finding an object of type UILabel class than it is shown as below.

for (UIView *subView in [weeklyViewA subviews]) {
            if ([subView isKindOfClass:[UILabel class]]) {
                NSLog(@"label class :: %@", [subView description]);
            }
        }
like image 40
Jekil Patel Avatar answered Oct 01 '22 19:10

Jekil Patel


Swift answer

For this case, I think we can use Swift's first.where syntax, which is more efficient than filter.count, filter.isEmpty.

Because when we use filter, it will create a underlying array, thus not effective, imagine we have a large collection.

So just check if a view's subViews collection contains a specific kind of class, we can use this

let containsBannerViewKind = view.subviews.first(where: { $0 is BannerView }) != nil

which equivalent to: find me the first match to BannerView class in this view's subViews collection. So if this is true, we can carry out our further logic.

Reference: https://github.com/realm/SwiftLint/blob/master/Rules.md#first-where

like image 28
Vinh Nguyen Avatar answered Oct 01 '22 19:10

Vinh Nguyen