我找到了这段代码(用appdelegate编写的应用程序)。我想要的只是让它支持另一个视图(我创建它)。
代码:
- (IBAction)swap
{
NSArray *subs = [window subviews];
[[subs objectAtIndex:0] removeFromSuperview];
if([subs objectAtIndex:0] == view2){
[window addSubview:view1];
} else if([subs objectAtIndex:0] == view1){
[window addSubview:view2];
}
}
答案 0 :(得分:1)
假设视图1,2和3是唯一的视图 -
- (IBAction)swap
{
[window sendSubviewToBack:[[window subviews] lastObject]];
}
或者,改变方向
- (IBAction)swap
{
[window bringSubviewToFront:[[window subviews] objectAtIndex:0]];
}
答案 1 :(得分:0)
- (IBAction)swap
{
NSArray *subs = [window subviews];
UIView *currentView = (UIView *)[subs objectAtIndex:0];
[currentView removeFromSuperview];
if(currentView == view1){
[window addSubview:view2];
} else if(currentView == view2){
[window addSubview:view3];
} else
[window addSubview:view1];
}
}
答案 2 :(得分:0)
如果你不想用IF ELSE折磨你的自我,你可以使用一系列视图并迭代它们。
NSArray *myViews = [NSArray arrayWithObjects:view1, view2, view3, nil];
NSInteger nextIndex = [myViews indexOfObject:[[window subviews] objectAtIndex:0]] + 1;
nextIndex = (nextIndex % [myViews count]); // to loop around if reached the end
[window addSubview:[myViews objectAtIndex:nextIndex]];
您可以对视图数组做一些聪明的事情,这样您就不会在每次交换时重新创建它。