• 点击按钮实现切换控制器的实现


    效果实现如下所示:

    实现代码如下:

    #import "ViewController.h"

    #import "ViewController1.h"

    #import "ViewController2.h"

    #import "ViewController3.h"

    #define kScreenWidth [UIScreen mainScreen].bounds.size.width

    #define kScreenHeight [UIScreen mainScreen].bounds.size.height

     

    @interface ViewController ()

     

    @property (nonatomic,strong) UIViewController *currentVc;

     

    @end

     

    @implementation ViewController

     

    - (void)viewDidLoad {

        [super viewDidLoad];

        // Do any additional setup after loading the view, typically from a nib.

        self.view.backgroundColor = [UIColor yellowColor];

        

        [self creatUI];

        [self addChildVC];

        

    }

    - (void)addChildVC{

        [self addChildViewController:[[ViewController1 alloc]init]];

        [self addChildViewController:[[ViewController2 alloc]init]];

        [self addChildViewController:[[ViewController3 alloc]init]];

     }

     

    - (void)creatUI{

      

        CGFloat width = kScreenWidth / 3;

        

        for (NSInteger i =0 ; i < 3; i++) {

            

            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];

            button.frame = CGRectMake(i * width,0,width,100);

            

            button.backgroundColor = [UIColor purpleColor];

            [button setTitle:[NSString stringWithFormat:@"按钮%ld",i + 1] forState:UIControlStateNormal];

            button.tag = i+ 1;

            

            //生成随机颜色

            button.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];

            [button addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];

            [self.view addSubview:button];

            

        }

    }

     

     

    - (void)pressBtn:(UIButton *)button{

        

        /*移除当前控制器*/

        [self.currentVc.view removeFromSuperview];

        

        //NSInteger index = [button.superview.subviews indexOfObject:button];

        

        //根据tag值设置当前控制器

        self.currentVc = self.childViewControllers[button.tag - 1];

        

        //设置尺寸

        self.currentVc.view.frame = CGRectMake(0, 100, kScreenWidth, kScreenHeight);

        

        //添加到控制器上

        [self.view addSubview:self.currentVc.view];

        

    }

     

     

  • 相关阅读:
    PTA9
    PTA8
    第七周
    第六周
    第五周
    PTA4
    2019第三次作业
    第十周课程总结
    第九周课程总结&实验报告(七)
    第八周课程总结&实验报告(六)
  • 原文地址:https://www.cnblogs.com/pengsi/p/5464939.html
Copyright © 2020-2023  润新知