我以编程方式创建了一个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或属性操作按钮。任何想法吗?
您没有正确使用指针。首先,将"按钮"指针设置为_homeButton。在第三行,你将"button"指针设置为一个新的UIButton。
基本上,这:
button = [UIButton buttonWithType:UIButtonTypeCustom];
抵消了
UIButton *button = _homeButton;
您没有在代码中分配_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;