UIButton无法一直表现出来

时间:2015-01-11 14:31:58

标签: ios uiview uibutton

我创建了一个UIButton并添加到我的视图中:

btn=[[UIButton alloc] init];
[btn setFrame:CGRectMake(0,rect.size.height-52, 70, 52)];
btn.imageEdgeInsets = UIEdgeInsetsMake(0,13,16,0);
btn.titleEdgeInsets = UIEdgeInsetsMake(35,-42,0, 0);
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view.window addSubview:btn];

-(void)doEnable:(BOOL)enable{
    if(enable){
      [btn setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal];
      [btn setImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateNormal];
      [btn setTitle:@"enter" forState:UIControlStateNormal];
      [btn setHidden:NO];

    //    [self.view bringSubviewToFront:_turn_button];
    }
    else{
      [btn setBackgroundImage:nil forState:UIControlStateNormal];
      [btn setImage:nil forState:UIControlStateNormal];
      [btn setTitle:@"  " forState:UIControlStateNormal];
      btn.hidden = YES;
    }
}

WillDidAppear中调用带有YES的doEnable和带有NO的WillDidDisappear,然后当我进入视图时,按钮应显示在左下角。

奇怪的是,有时它可以出现,有时却不能出现。但即使它无法显示,它仍然可以接收触摸事件,始终调用btnClicked方法。为什么呢?

2 个答案:

答案 0 :(得分:0)

我认为您应该在viewDidAppear和viewDidDisappear中调用doEnable方法作为viewWillAppear中的更新UI,并且无法保证viewWillDisappear,因为您的视图可能尚未加载。

答案 1 :(得分:0)

改变这个:

  

[self.view.window addSubview:btn];

对此:

  

[self.view addSubview:btn];