自定义控制器切换

1.先添加一个view(菜单栏)并添加约束


2.再往 菜单栏view中,添加3个按钮控件,等高等宽


3.让菜单栏中3个按钮都连线到控制器的buttonclick方法上,并创建3个控制器


4.父控制代码

//
//  ViewController.m


#import "ViewController.h"
#import "OneViewController.h"
#import "TwoViewController.h"
#import "ThreeViewController.h"

@interface ViewController ()
/** 正在显示的控制器 */
@property (nonatomic, weak) UIViewController *showingVc;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 通过addChildViewController添加的控制器都会存在于childViewControllers数组中
    [self addChildViewController:[[OneViewController alloc] init]];
    [self addChildViewController:[[TwoViewController alloc] init]];
    [self addChildViewController:[[ThreeViewController alloc] init]];
}

- (IBAction)buttonClick:(UIButton *)sender
{
    // 移除其他控制器的view
    [self.showingVc.view removeFromSuperview];
    
    // 获得控制器的位置(索引)
    NSUInteger index = [sender.superview.subviews indexOfObject:sender];
    
    // 添加控制器的view
    self.showingVc = self.childViewControllers[index];
    self.showingVc.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
    [self.view addSubview:self.showingVc.view];
}

@end
最后效果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值