我以编程方式创建了一个UIButton并将其放入属性中:
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];
现在,让我们检查选择器:
由于某种原因,这有效:
- (void)checkHide:(UIButton *)sender {
[sender removeFromSuperview];
}
但这并不是:
- (void)checkHide:(UIButton *)sender {
[_homeButton removeFromSuperview];
}
为什么我需要后一种解决方案?因为我想通过点击另一个按钮来删除此特定按钮。所以,我无法从中获得任何发件人。尽管如此,checkHide
方法中的代码仍然正在执行,例如,我无法使用iVar或属性操作按钮。有什么想法吗?
答案 0 :(得分:1)
您不在代码中指定_homeButton。试试这个:
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;
答案 1 :(得分:1)
您没有正确使用指针。首先,您要设置"按钮"指向_homeButton的指针。在第三行,您将设置"按钮"指向新UIButton的指针 基本上,这个:
button = [UIButton buttonWithType:UIButtonTypeCustom];
取消了这个:
UIButton *button = _homeButton;
请参阅Joel的答案以获得可能的解决方案。