ios - 无法通过 iVar/property 访问 UIButton

标签 ios objective-c properties uibutton instance-variables

我以编程方式创建了一个 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。在第三行中,您将“按钮”指针设置为新的 UIButton。
基本上,这是:

button = [UIButton buttonWithType:UIButtonTypeCustom];

取消这个:

UIButton *button = _homeButton;

有关可能的解决方案,请参阅 Joel 的回答。

关于ios - 无法通过 iVar/property 访问 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25123226/

相关文章:

Java 异常和 Objective C NSError

ios - 如何将此字符串 @"base+unit1+unit2(unit3+unit4)"转换为数组

ios - UITableViewCell 上 2 个 UILabel 的布局

ios - FMDB:更新时数据库被锁定

ios - 以编程方式快速按下 UIBarButtonItem?

ios - 从没有 xcworkspace 的 .APP 包构建 IPA

iphone - 从 UILabel 中删除最后一个值?

ios - 在 UIImagePickerController 委托(delegate)中识别不同的选择器

c# - 属性 - 按值还是引用?

java - 在 Java 中存储/添加/删除一组简单数据的最佳方法