zoukankan      html  css  js  c++  java
  • 点击按钮实现切换控制器的实现

    效果实现如下所示:

    实现代码如下:

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

        

    }

     

     

  • 相关阅读:
    static,const,extern,以及全局常量
    ios开发之级联菜单(两个tableView实现)
    ios开发零散知识点总结
    ios开发static关键字的理解
    ios开发清除SDWebImage图片缓存
    python
    Scapy 伪造网络数据包
    LeetCode-73. Set Matrix Zeroes
    排序算法系列:Shell 排序算法
    Android中级第十一讲之MotionEvent的分发、拦截机制分析
  • 原文地址:https://www.cnblogs.com/pengsi/p/5464939.html
Copyright © 2011-2022 走看看