使用MGSplitViewController建立多个detailViewController的工程

郦良才
2023-12-01

习惯了不用xib文件,写的是个纯代码的工程,所以模板选择的“empty application”


1、建立好空工程后,导入MGSplitViewController的三个类

ARC工程别忘了添加-fno-objc-arc

2、AppDelegate的配置= =

(1).h文件

a) 添加一个属性

@property (nonatomic, retain) MGSplitViewController *splitViewController;

(需要包含#import "MGSplitViewController.h")


(2).m文件

a) 需要包含最初显示的rootViewController和首个detailViewController

b) - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //左边管理界面
    RootViewController* root = [[RootViewController alloc] init];
    UINavigationController* rootNav = [[UINavigationController alloc] initWithRootViewController:root];
    //右边第一个详情界面
    firstDetailViewController* first = [[firstDetailViewController alloc] init];
    UINavigationController* detailNav = [[UINavigationController alloc] initWithRootViewController:first];
    
    self.splitViewController = [[MGSplitViewController alloc] init];
    self.splitViewController.viewControllers = [NSArray arrayWithObjects:rootNav, detailNav, nil];
    self.splitViewController.showsMasterInPortrait = YES;//竖屏时也显示,显示宽度需要设置MGSplitViewController的MG_DEFAULT_SPLIT_POSITION宏定义值
    self.window.rootViewController = self.splitViewController;

    
    
    return YES;
}

这里简单说明一下,splitViewController的viewControllers必须是两个,分别表示的是左边的管理页面和右边的详情页面,这个根据需要任意设置。后面点击左边的rootViewController变换右边的detailViewController也是通过重新设置这一属性实现的

这个时候运行,应该就可以看到初始时分屏的效果了


3、变换左后的页面

(1)AppDelegate.h中添加三个方法

#pragma mark -- toolKits
-(void)swtichDetailViewController:(id)controller;//切换右边详情试图
-(void)toggleMasterViewController;//切换rootViewController的显示和隐藏
+(AppDelegate*)sharedDelegate;


(2)AppDelegate.m中实现

#pragma mark -- toolKits
-(void)swtichDetailViewController:(id)controller
{
    //保留原有的rootViewController
    id nav = [self.splitViewController.viewControllers objectAtIndex:0];
    //新的detailViewController
    UINavigationController* nav2 = [[UINavigationController alloc] initWithRootViewController:controller];
    self.splitViewController.viewControllers = [NSArray arrayWithObjects:nav, nav2, nil];
}

-(void)toggleMasterViewController//切换rootViewController的显示和隐藏
{
    [self.splitViewController toggleMasterView:nil];
}

+(AppDelegate*)sharedDelegate
{
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}



在需要的地方调用[[AppDelegate sharedDelegate] swtichDetailViewController:secondDetailVC];就可以了

 类似资料: