下面的代碼顯示如何在容器視圖中切換控制器。在IB中,我從一個標籤模板開始,在FirstViewController的頂部添加導航欄和工具欄,並將分段控件添加到工具欄。然後,我在視圖中添加了一個容器視圖(在對象列表中的常規視圖旁邊),並將其大小設置爲佔據標籤欄和工具欄之間的所有空間。我在容器視圖和導航欄的標題項中創建了插座,並將方法changeControllers:連接到分段控件。當你添加容器視圖時,你可以通過嵌入segue自動獲得一個相同大小的視圖控制器。我添加了兩個視圖控制器,將其大小更改爲「Freeform」,並將其大小調整爲與嵌入式控制器(320x411)相同。此大小更改僅用於IB中的佈局目的,您仍然必須在將代碼中的視圖添加到容器時調整代碼中的視圖大小,如下所示。這個代碼是在FirstViewController中,帶有容器視圖的控制器:
@interface FirstViewController()
@property (weak,nonatomic) IBOutlet UIView *containerView;
@property (strong,nonatomic) UIViewController *embeddedVC;
@property (strong,nonatomic) UIViewController *secondVC;
@property (strong,nonatomic) UIViewController *thirdVC;
@property (strong,nonatomic) UIViewController *currentController;
@property (weak,nonatomic) IBOutlet UINavigationItem *titleItem;
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.embeddedVC = self.childViewControllers.lastObject;
self.currentController = self.embeddedVC;
self.titleItem.title = self.currentController.title;
}
-(IBAction)ChangeControllers:(UISegmentedControl *)sender {
switch (sender.selectedSegmentIndex) {
case 0:{
if (![self.currentController isEqual:self.embeddedVC]) {
self.embeddedVC.view.frame = self.containerView.bounds;
[self addChildViewController:self.embeddedVC];
[self moveToNewController:self.embeddedVC];
}
break;
}
case 1:{
if (! self.secondVC) {
self.secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"Second"];
}
if (![self.currentController isEqual:self.secondVC]) {
self.secondVC.view.frame = self.containerView.bounds;
[self addChildViewController:self.secondVC];
[self moveToNewController:self.secondVC];
}
break;
}
case 2:{
if (! self.thirdVC) {
self.thirdVC = [self.storyboard instantiateViewControllerWithIdentifier:@"Third"];
}
if (![self.currentController isEqual:self.thirdVC]) {
self.thirdVC.view.frame = self.containerView.bounds;
[self addChildViewController:self.thirdVC];
[self moveToNewController:self.thirdVC];
}
break;
}
default:
break;
}
}
-(void)moveToNewController:(id) newController {
[self.currentController willMoveToParentViewController:nil];
[self transitionFromViewController:self.currentController toViewController:newController duration:.6 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{}
completion:^(BOOL finished) {
[self.currentController removeFromParentViewController];
[newController didMoveToParentViewController:self];
self.currentController = newController;
self.titleItem.title = self.currentController.title;
}];
}
它在這裏對這個問題不以爲然,要問同樣的問題兩次。話雖如此,如果我理解了這個問題,我會盡力幫助你,但我不知道。 「爲每個分段按鈕創建視圖」是什麼意思?你是指你的一個按鈕的每個部分?你的意思是什麼意思?您想在點擊某個細分受衆羣時轉到其他控制器嗎? – rdelmar 2013-02-13 19:44:04
另一個問題。看起來你在第一個控制器中有一個導航欄和一個工具欄。那是對的嗎?你用什麼導航欄?對於它的標題時間? – rdelmar 2013-02-13 21:45:17
s我想在一個細分受到攻擊時轉到不同的控制器!但應顯示在同一個控制器中.. – 2013-02-14 06:24:41