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

6

6

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

Terrorize answered 26/6, 2013 at 12:34 Comment(0)
M
25
for(UIView *aView in yourView.subviews){
    if([aView isKindOfClass:[YourClass class]]){
       //YourClass found!!
    }
}
Marabou answered 26/6, 2013 at 12:37 Comment(1)
This doesn't solve when there are several same type Views, like UILabel in the subviews. try to add tag on the view, and use viewWithTag to access the subview later.Quarterage
Z
3

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]);
            }
        }
Zoniazoning answered 26/6, 2013 at 13:10 Comment(0)
S
2

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

Sinistrodextral answered 21/9, 2017 at 3:55 Comment(0)
B
0

This is the swift version for checked solution :

Example for UITextField :

    for (_, view) in self.myView.subviews.enumerate(){
        if view.isKindOfClass(UITextField){
            //Here we go
        }
    }
Blanchette answered 1/7, 2016 at 13:36 Comment(0)
O
0

in my opinion.isMemberOfClass:is better than isKindOfClass:,for example:

for (BadgeButton *button in self.subviews) {
    if ([button isMemberOfClass:[BadgeButton class]]) {
        button.selected = NO;
    }
}
Orlop answered 17/5, 2017 at 14:7 Comment(2)
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From ReviewPier
@JonRose Yeah,I had improved my answer.Orlop
A
0

Swift 4.2: You can try below code:

let allsubviews = self.view.subviews
allsubviews.forEach { (view) in
   if view.isKind(of: UIScrollView.self){
       //current view is UIScrollview
   }
}
Alcahest answered 29/1, 2019 at 19:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.