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


    效果实现如下所示:

    实现代码如下:

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

        

    }

     

     

  • 相关阅读:
    spring boot的@RequestParam和@RequestBody的区别
    SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
    Required String parameter is not present
    Spring Boot 日志记录 SLF4J
    400错误,Required String parameter 'paramter' is not present
    初学 Spring boot 报错 Whitelabel Error Page 404
    Powershell获取WMI设备清单
    Powershell快速入门
    perl的Sys::Syslog模块(openlog,syslog,closelog函数,setlogsock)-自定义日志
    制作Windows10政府版的小白教程
  • 原文地址:https://www.cnblogs.com/pengsi/p/5464939.html
Copyright © 2020-2023  润新知