如何在iphone上点击按钮显示uiview

时间:2011-08-11 04:49:43

标签: iphone objective-c

我有一个应用程序,其中我有一个uiview,上面有两个按钮。我已经设置了我的uiview框架。

newview = [[UIView alloc]initWithFrame:CGRectMake(0,350,320,70)];

并将其设置为我的主视图

[self.view addSubview:newview];

然后在这个新视图中添加了两个按钮。新视图左侧的一个按钮和新视图右侧的其他按钮。

这是我的按钮代码

leftnavbutton= [[UIButton buttonWithType:UIButtonTypeCustom] retain];
            leftnavbutton.backgroundColor = [UIColor clearColor];
            [leftnavbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];

UIImage *buttonImageleft = [UIImage imageNamed:@"previous_large.png"];
            //UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];

[leftnavbutton setBackgroundImage:buttonImageleft forState:UIControlStateNormal];
            [leftnavbutton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
[leftnavbutton setFrame:CGRectMake(23, 28, 8, 44)];
            [newview addSubview:leftnavbutton];  



rightnavbutton= [[UIButton buttonWithType:UIButtonTypeCustom] retain];
            rightnavbutton.backgroundColor = [UIColor clearColor];
            [rightnavbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];

UIImage *buttonImageright = [UIImage imageNamed:@"next_large.png"];
            //UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];            

[rightnavbutton setBackgroundImage:buttonImageright forState:UIControlStateNormal];         

[rightnavbutton addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];           

[rightnavbutton setFrame:CGRectMake(275, 28, 8, 44)];
[newview addSubview:rightnavbutton];  

所以现在我想要点击这些按钮。新视图应该取代我的新视图。 例如,当我在新视图中运行我的应用程序时,显示从xml获取的当前条件。因此,当我点击右键时,应打开一个新视图,该视图应该获取forecsat条件标记fron xml并显示在其上,当我单击右键时它应该再次显示当前条件。即它应该是循环的。如果我点击左键,则应显示预测条件。这怎么可能?

1 个答案:

答案 0 :(得分:1)

您需要做的就是用另一个视图替换newView。为此,您应首先设置newView的tag

newview = [[UIView alloc]initWithFrame:CGRectMake(0,350,320,70)];
newView.tag = 7; // set whatever number you want
[self.view addSubview:newview];

playAction中,抓住newView并将其从superView中删除。然后在其位置添加另一个视图。

-(void)playAction:(id)sender
{
     UIView* newView = [self.view viewWithTag:7];
     [newView removeFromSuperView];

     //create and add the new new view that should replace new view. Use the same frame.
     UIView* newnewview = [[UIView alloc]initWithFrame:CGRectMake(0,350,320,70)];
     newnewView.tag = 7; // set whatever number you want
     [self.view addSubview:newnewview];

      //Add the left & right buttons again, as they were removed when newView was removed
      ... code to add buttons...
}

同样可以实现play:方法。