編集で正しい答えを見つけました。私が理解していることから、側面のボタンは別のタブバーコントローラーに似ていますが、メインのタブバーコントローラー内にネストされていますか?
おなじみのパターンなので、同じパターンに従うこともできます。検索ビュー コントローラーは、各フォーム オプションを表すビュー コントローラーの配列を持つコンテナー ビュー コントローラーとして機能する必要があります。
オプションを切り替えるときに、ビュー階層 (を使用addSubview
)およびビュー コントローラー階層 (リンクの「子の追加と削除」のコードを使用) から適切なビュー コントローラー ビューを追加/削除します。View Controller 階層は、子コントローラーで viewDidAppear などが確実に呼び出されるようにするために重要です。
例として、メイン ビュー コントローラーに一連のボタンがあり、それぞれが同じアクションにリンクされており、ビュー コントローラーの配列が含まれている簡単なデモ プロジェクトを作成しました。container
含まれているView Controllerは、この例で呼び出されるサブビュー内に保持されます。これは、上のスクリーンショットの右側の領域のサイズになります。
viewDidLoad
子コントローラーは、コンテナー ビュー コントローラーで次のように設定されます。
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *buttons;
@property (weak, nonatomic) IBOutlet UIView *container;
@property (nonatomic,strong) NSArray *viewControllers;
@property (nonatomic, strong) UIViewController *currentChild;
@end
@implementation JRTViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
for (UIButton *button in self.buttons)
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
NSMutableArray *children = [NSMutableArray new];
for (int i = 0; i < 4; i++)
{
ContainedViewController *child = [ContainedViewController new];
child.name = [NSString stringWithFormat:@"Form %d",i + 1];
[children addObject:child];
}
self.viewControllers = [children copy];
[self buttonTapped:self.buttons[0]];
}
ここでは、同じビュー コントローラー クラスの 4 つのインスタンスを使用しました。含まれているのは、選択しているフォームを示すラベルだけです。本当に、それぞれに異なるクラスがあります。また、最初のボタンのアクション メソッドを送信して、最初のビュー コントローラーを「選択」しました。アクション メソッドはこれを行います。
- (IBAction)buttonTapped:(UIButton *)sender
{
NSUInteger index = [self.buttons indexOfObject:sender];
if (index != NSNotFound)
self.currentChild = self.viewControllers[index];
}
これにより、View Controller アレイから適切な VC が選択されます。setter メソッドはこれを行います。
-(void)setCurrentChild:(UIViewController *)currentChild
{
if (currentChild == _currentChild) return;
// Remove the old child
[_currentChild willMoveToParentViewController:nil];
[_currentChild.view removeFromSuperview];
[_currentChild removeFromParentViewController];
[_currentChild didMoveToParentViewController:nil];
// Add the new one
[currentChild willMoveToParentViewController:self];
[self.container addSubview:currentChild.view];
NSDictionary *views = @{@"view":currentChild.view};
[self.container addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[view]|" options:0 metrics:nil views:views]];
[self.container addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:views]];
[self addChildViewController:currentChild];
[currentChild didMoveToParentViewController:self];
_currentChild = currentChild;
}
ビューコントローラー階層を設定し、ビューに追加し、制約を使用してコンテナーを満たすようにします。
この例では、4 つのボタンと 4 つの子ビュー コントローラーをハードコーディングしました。これは、子ビュー コントローラーの追加と切り替えを示していたからです。実際には、View Controller の配列を割り当てると、コンテナーが独自のボタンの配列を作成するタブ バー コントローラーのようになります。