How to check if subview is button or not
Asked Answered
M

4

8

I am developing an application. In that I get all subviews of UITableViewCell.

The code for this one is:

    (void)listSubviewsOfView:(UIView *)view {

    // Get the subviews of the view
         NSArray *subviews = [view subviews];

    // Return if there are no subviews
    if ([subviews count] == 0) return;

    for (UIView *subview in subviews) {

        NSLog(@"%@", subview);

        // List the subviews of subview
        [self listSubviewsOfView:subview];
    }
}

But my problem is how to find out button from that subviews list. Please tell me how to solve this one.

Maldon answered 19/4, 2012 at 5:26 Comment(0)
C
19

You can iterate through all subviews like this.

for (id subview in subviews) {
   if ([subview isKindOfClass:[UIButton class]]) {
      //do your code
   }
}
Cly answered 19/4, 2012 at 5:29 Comment(0)
E
13

Swift

for subview in view.subviews {
    if subview is UIButton {
        // this is a button
    }
}
Edaphic answered 31/8, 2017 at 8:10 Comment(0)
F
2

Check if the subview is a button with is AnyClass, isKind(of aClass: AnyClass) or isMember(of aClass: AnyClass) API.

Using is-

for subview in self.view.subviews{
      if subview is UIButton{
            //do whatever you want
      }
}

Using isMember(of:)-

for subview in self.view.subviews{
     if subview.isMember(of: UIButton.self){
          //do whatever you want
     }
}

Using isKind(of:)-

for subview in self.view.subviews{
    if subview.isKind(of: UIButton.self){
        //do whatever you want
    }
}
Fritillary answered 19/4, 2019 at 14:16 Comment(0)
S
-2

To expand on the 'do your code' part of Martin's answer. Once I got the subview, I wanted to test whether it was the right button and then remove it. I can't check the titleLabel of the button directly by using subview.titleLabel so I assigned the subview to a UIButton and then checked the button's titleLabel.

- (void)removeCheckboxes {

    for ( id subview in self.parentView.subviews ) {
        if ( [subview isKindOfClass:[UIButton class]] ) {
            UIButton *checkboxButton = subview;
            if ( [checkboxButton.titleLabel.text isEqualToString:@"checkBoxR1C1"] )    [subview removeFromSuperview];
        }
    }

}
Sialoid answered 14/5, 2013 at 22:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.