0

我的 viewWillAppear 方法调用“-(void)doSomething”。

- (void)doSomething
{
    Y4AppDelegate * delegate = (Y4AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(delegate.booSomeValue == 0) {
        UIButton * aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [aButton setFrame:CGRectMake(20,360,280,40)];
        [aButton setTitle:@"Title"
                 forState:UIControlStateNormal];
        [aButton addTarget:self
                    action:@selector(mySelector)
          forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:aButton];
    }
}

它可以工作,但 aButton 仍然可见。我该怎么做才能隐藏aButton?我有三个 UIViewController。第三,我将 delegate.booSomeValue 设置为 true。当我回到之前的 UIViewController 时,我调用了这个 viewWillAppear,但是 aButton 是可见的。我想隐藏它。

4

2 回答 2

1

问题是您添加了一次,当您返回它时,您并没有添加第二个,但是您添加的第一个仍然存在,因此您必须将其删除。

为此,您首先需要创建一个属性来存储按钮,并检查它是否存在

if ( ... show button condition ... ) {

    if (!aButton) {
        ... create and show button ...
    }
}
else {
    if (aButton) {
         [aButton removeFromSuperview];
         aButton = nil;
    }
}
于 2013-01-25T14:43:25.500 回答
1

将此代码移动到 viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad]
    UIButton * aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    aButton.tag = 101;
    [aButton setFrame:CGRectMake(20,360,280,40)];
    [aButton setTitle:@"Title"
             forState:UIControlStateNormal];
    [aButton addTarget:self
                action:@selector(mySelector)
      forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:aButton];
}

- (void)doSomething
{
    Y4AppDelegate * delegate = (Y4AppDelegate *)[[UIApplication sharedApplication] delegate];
    UIButton * aButton =  (UIButton*)[self.view viewWithTag:101]; 
    aButton.hidden = delegate.booSomeValue;
}
于 2013-01-25T14:48:28.350 回答