如何工作viewWillAppear?

时间:2013-01-25 14:39:35

标签: objective-c uiviewcontroller uiapplicationdelegate

我的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];
    }
}

它可以工作,但是按钮仍然可见。我该怎么做来隐藏一个按钮?我有三个UIViewController。在第三个我将delegate.booSomeValue设置为true。当我回到之前的UIViewController时,我称之为viewWillAppear但是aButton是可见的。我想隐藏它。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

问题是你添加了一次,当你回到它时,你没有添加第二个,但你添加的第一个仍然存在,所以你必须删除它。

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

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

    if (!aButton) {
        ... create and show button ...
    }
}
else {
    if (aButton) {
         [aButton removeFromSuperview];
         aButton = nil;
    }
}