How to check if subview is a button or not

I am developing an application. In this, I get all the subitems of the UITableViewCell.

Code for this:

    (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 the button from this list of subviews. Please tell me how to solve this problem.

+5
source share
4 answers

You can iterate over all similar objects.

for (id subview in subviews) {
   if ([subview isKindOfClass:[UIButton class]]) {
      //do your code
   }
}
+15
source

swift

for subview in view.subviews {
    if subview is UIButton {
        // this is a button
    }
}
+5
source

, is AnyClass is AnyClass, isKind(of aClass: AnyClass) isMember ( aClass: AnyClass) API.

is-

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

isMember (of:) -

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

isKind (of:) -

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

To expand part of Martin's “make your code” answer. As soon as I got a subview, I wanted to check if it was the right button, and then delete it. I cannot check the titleLabel of the button directly using subview.titleLabel, so I assigned a subview to UIButton and then checked the titleLabel button.

- (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];
        }
    }

}
-2
source

All Articles