开发者

modify this code to support another view

I found this code (written in appdelegate for an application). All I want is to just let it support one more 开发者_如何学编程view ( I created it).

The code :

- (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];
    }
}


Assuming views 1, 2, and 3 are the only views -

- (IBAction)swap
{
    [window sendSubviewToBack:[[window subviews] lastObject]];
}

Or, reversing the direction

- (IBAction)swap
{
    [window bringSubviewToFront:[[window subviews] objectAtIndex: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];
    }
}


If you do not want to torture your self with IF ELSEs you could use an array of views and iterate through them.

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]];

You can do something smart about the array of views so you do not recreate it every time you swap.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜