Richard Topchii
Richard Topchii

Reputation: 8165

Cannot access UIButton through iVar / property

I created an UIButton programmatically and put it into a property:

    UIButton *button = _homeButton; 
    UIImage *image = [UIImage imageNamed:@"homeButton"];
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(checkHide:) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    button.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, image.size.width, image.size.height);
    [[self superview] insertSubview:button belowSubview:self];

Now, lets check the selector:
by some reason, this works:

- (void)checkHide:(UIButton *)sender {
        [sender removeFromSuperview];
}

but this doesn't:

- (void)checkHide:(UIButton *)sender {
    [_homeButton removeFromSuperview];
}  

Why do I need the latter solution? Because I would like to remove this particular button by tapping another button. So, I can't get any sender from it. Still, the code in checkHide method is being executed anyway, the case, I cannot manipulate with button using iVar or property. Any thoughts?

Upvotes: 0

Views: 95

Answers (2)

Justin Moser
Justin Moser

Reputation: 2005

You are not using your pointers correctly. First you are setting your "button" pointer to your _homeButton. In the third line you are then setting your "button" pointer to a new UIButton.
Basically, this:

button = [UIButton buttonWithType:UIButtonTypeCustom];

cancels out this:

UIButton *button = _homeButton;

See Joel's answer for a possible solution.

Upvotes: 1

Joel
Joel

Reputation: 16124

You don't assign _homeButton in your code. Try this:

UIImage *image = [UIImage imageNamed:@"homeButton"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(checkHide:) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:image forState:UIControlStateNormal];
button.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, image.size.width, image.size.height);
[[self superview] insertSubview:button belowSubview:self];
_homeButton = button;

Upvotes: 1

Related Questions