[英]Tabbarcontroller add tabs programmatically
對於我正在構建的應用程序,我的所有視圖都在情節提要中完成,並且它使用tabbarcontrolller在不同的視圖之間切換。 我有一個視圖,我想以編程方式添加到已經具有三個項目的此現有標簽欄。 如何以編程方式添加此選項卡並使其他選項卡通過情節提要。
更多:我按照您的意思做了,但是當我添加它仍然僅具有三個選項卡而不是添加第四個選項卡時,什么也沒有發生,這是我為選項卡欄控制器提供的代碼
@interface TheTabBarController ()
@end
@implementation TheTabBarController
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
UIViewController *viewController = [[CrewsViewController alloc]init];
NSMutableArray *tempArray = [self.tabBarController.viewControllers mutableCopy];
[tempArray addObject:viewController];
self.tabBarController.viewControllers = tempArray;
}
@end
您可以通過在標簽欄控制器的viewControllers
數組中添加一個新控制器來做到這一點。 因此,請以適合您的方式來實例化新控制器。 標簽欄控制器的viewControllers
屬性是一個不可變的數組,因此您需要從該數組創建一個可變數組,向其中添加控制器,然后將該數組設置為標簽欄控制器的viewControllers
數組。
UIViewController *newController = [[UIViewController alloc] init]; // or however is appropriate to instantiate your controller
NSMutableArray *tempArray = [self.tabBarController.viewControllers mutableCopy];
[tempArray addObject:newController];
self.tabBarController.viewControllers = tempArray;
嘗試這個:
- (void)viewDidLoad {
[super viewDidLoad];
UIViewController *view1 = [[UIViewController alloc] init];
UIViewController *view2 = [[UIViewController alloc] init];
UIViewController *view3 = [[UIViewController alloc] init];
NSMutableArray *tabViewControllers = [[NSMutableArray alloc] init];
[tabViewControllers addObject:view1];
[tabViewControllers addObject:view2];
[tabViewControllers addObject:view3];
[self setViewControllers:tabViewControllers];
//can't set this until after its added to the tab bar
view1.tabBarItem =
[[UITabBarItem alloc] initWithTitle:@"view1"
image:[UIImage imageNamed:@"view1"]
tag:1];
view2.tabBarItem =
[[UITabBarItem alloc] initWithTitle:@"view2"
image:[UIImage imageNamed:@"view3"]
tag:2];
view3.tabBarItem =
[[UITabBarItem alloc] initWithTitle:@"view3"
image:[UIImage imageNamed:@"view3"]
tag:3];
}
swift4:
func viewDidLoad() {
super.viewDidLoad()
let view1 = UIViewController()
let view2 = UIViewController()
let view3 = UIViewController()
var tabViewControllers = [AnyHashable]()
tabViewControllers.append(view1)
tabViewControllers.append(view2)
tabViewControllers.append(view3)
if let aControllers = tabViewControllers as? [UIViewController] {
viewControllers = aControllers
}
//can't set this until after its added to the tab bar
`view1.tabBarItem = UITabBarItem(title: "view1", image: UIImage(named: "view1"), tag: 1)
view2.tabBarItem = UITabBarItem(title: "view2", image: UIImage(named: "view3"), tag: 2)
view3.tabBarItem = UITabBarItem(title: "view3", image: UIImage(named: "view3"), tag: 3)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.