UI2_视图切换

//
//  ViewController.m
//  UI2_视图切换
//
//  Created by zhangxueming on 15/7/1.
//  Copyright (c) 2015年 zhangxueming. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    NSInteger _tagIndex;//记录当前显示的视图
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UILabel *redLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 320, 100)];
    redLabel.backgroundColor = [UIColor redColor];
    redLabel.tag = 1;
    redLabel.text = @"红色";
    redLabel.textAlignment = NSTextAlignmentCenter  ;
    [self.view addSubview:redLabel];
    
    UILabel *blueLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 120, 320, 100)];
    blueLabel.backgroundColor = [UIColor blueColor];
    blueLabel.tag = 2;
    blueLabel.text = @"蓝色";
    blueLabel.textAlignment = NSTextAlignmentCenter  ;
    [self.view addSubview:blueLabel];
    
    UILabel *greenLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 140, 320, 100)];
    greenLabel.backgroundColor = [UIColor greenColor];
    greenLabel.tag = 3;
    greenLabel.text = @"绿色";
    greenLabel.textAlignment = NSTextAlignmentCenter  ;
    [self.view addSubview:greenLabel];
    
    UIButton *lastBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    lastBtn.frame = CGRectMake(40, 400, 100, 30);
    [lastBtn setTitle:@"上一张" forState:UIControlStateNormal];
    lastBtn.backgroundColor = [UIColor cyanColor];
    [lastBtn addTarget:self action:@selector(lastBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:lastBtn];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    nextBtn.frame = CGRectMake(self.view.frame.size.width-140, 400, 100, 30);
    [nextBtn setTitle:@"下一张" forState:UIControlStateNormal];
    nextBtn.backgroundColor = [UIColor cyanColor];
    [nextBtn addTarget:self action:@selector(nextBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
    
    //设置当前显示的视图
    _tagIndex = 3;
    
    self.view.backgroundColor = [UIColor blackColor];
}


- (void)lastBtnClicked
{
    _tagIndex--;
    if (_tagIndex<1) {
        _tagIndex = 3;
    }
    //根据传入的tag值取出对应的视图
    UILabel *label = (UILabel *)[self.view viewWithTag:_tagIndex];
    [self.view bringSubviewToFront:label];
}

- (void)nextBtnClicked
{
    _tagIndex++;
    if (_tagIndex>3) {
        _tagIndex = 1;
    }
    UILabel *label = (UILabel *)[self.view viewWithTag:_tagIndex];
    [self.view bringSubviewToFront:label];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
原文地址:https://www.cnblogs.com/0515offer/p/4638443.html