Button not clickable after adding as a subview to a UIView

12,441

Solution 1

check the frame of your UICustomButton object, and if self.customButton is out of its superView.

Solution 2

Make sure that the frame of the subview is within the frame of its superview. I encountered the issue twice and both times the frame of the subview was incorrect.

Share:
12,441
Zhen
Author by

Zhen

Updated on June 04, 2022

Comments

  • Zhen
    Zhen almost 2 years

    I have created a class called UICustomButton, which is a subclass of UIView. I added a UIButton to UIView as a subview as shown in my code below:

    -(id)initWithButtonType:(NSString *)type
    {
        self = [super init];
        if (self) 
        {
            self.customButton = [self setupButtonWithTitle:type andFrame:frame];
            [self addSubview:self.customButton];
            self.customButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    
        }
        return self;
    }
    

    The problem I am facing is that although the button appears, they are not clickable. Is there something wrong with the way I am adding the buttons to the UIView?

    enter image description here

    EDIT: To add on, I am using this custom button class instance to a cell:

    UICustomButton *customButton = [[UICustomButton alloc]initWithFrame:someFrame];
    [cell.contentView addSubView:customButton];