【问题标题】:Cannot access UIButton through iVar / property无法通过 iVar / 属性访问 UIButton
【发布时间】:2014-09-27 04:41:00
【问题描述】:

我以编程方式创建了一个 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 或属性使用按钮进行操作。有什么想法吗?

【问题讨论】:

    标签: ios objective-c properties uibutton instance-variables


    【解决方案1】:

    您没有正确使用指针。首先,您将“按钮”指针设置为 _homeButton。在第三行中,您将“按钮”指针设置为新的 UIButton。
    基本上是这样的:

    button = [UIButton buttonWithType:UIButtonTypeCustom];
    

    取消:

    UIButton *button = _homeButton;
    

    查看 Joel 的答案以获得可能的解决方案。

    【讨论】:

    • 谢谢你们!由于两个答案是用相同的解决方案同时发送的,我掷硬币。
    • 我认为 Joel 领先我 17 秒,但我不会告诉任何人。
    • 我听说了。我说。
    【解决方案2】:

    您没有在代码中分配 _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;
    

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2011-09-27
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多