在我的 iOS 应用程序中,选项卡项目的数量不会固定。这将由运行时间决定。假设,我必须显示 4 个选项卡,那么我将必须创建相同 UIViewController
运行时的 4 个实例(在 4 个不同的导航 Controller 中)。
以下是我们访问特定 View Controller 的操作:
id controller1 = [self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
[controller1 setTitle:@"Football"];
UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:controller1];
[arrControllers insertObject:nav1 atIndex:0];
我想要做的是让 4 个导航 Controller 实例具有相同 View Controller 的实例。所有 4 个 View Controller 将具有相同的功能来执行(一个将显示足球视频,一个将显示篮球视频..)意味着,在 Storyboard中,MyViewController
是一个 View Controller ,但需要创建不同的 View Controller 该 MyViewController
我该怎么做?我必须这样做的唯一原因是,选项卡栏的选项卡不会固定,这些选项卡将是动态的。
请分享任何有用的东西..
最佳答案
一个 View Controller 一次只能被另一个 View Controller 包含。即使情况并非如此,我怀疑您是否希望跨选项卡使用相同的实例,因为每次用户更改选项卡时您都会承担更改其状态的负担。
更简单的设置是创建具有唯一根的唯一导航 vcs 以响应来自服务器的数据,例如......
// you've figured out here that you need four tabs, based on
// a response from the server like...
NSArray *tabNames = @[ @"one", @"two", @"three" @"four"]; // from the server
NSArray *tabs = [@[] mutableCopy];
for (NSString *tabName in tabNames) {
MyViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
vc.title = tabName;
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
[tabs addObject:nav];
}
// here, tabs is an array of view controllers that can
// be assigned to the tabBar viewControllers property
关于ios - 创建 UIViewController 的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38205661/