I am trying to find a specific class object added as Subview to a UIView, but I could not find anything.
for(UIView *aView in yourView.subviews){
if([aView isKindOfClass:[YourClass class]]){
//YourClass found!!
}
}
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]);
}
}
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
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
}
}
in my opinion.isMemberOfClass:
is better than isKindOfClass:
,for example:
for (BadgeButton *button in self.subviews) {
if ([button isMemberOfClass:[BadgeButton class]]) {
button.selected = NO;
}
}
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
}
}
© 2022 - 2024 — McMap. All rights reserved.