我在UIViewController的導航欄中以編程方式創建了UISegmentedControl,我希望能夠在切換分段控件時切換視圖控制器。無法在2視圖控制器與分段控件之間切換
這是我到目前爲止有:
@interface TVExploreViewController : TVViewController
@property (nonatomic, strong) UISegmentedControl *scopeControl;
@property (nonatomic, assign) NSInteger scope;
@property (nonatomic, strong) UIViewController *premiumContentViewController;
@property (nonatomic, strong) UIViewController *trendingContentViewController;
@property (nonatomic, strong) UIViewController *currentViewController;
@end
TVExploreViewController的實現:
- (void)viewDidLoad {
[super viewDidLoad];
_scopeControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"TV & MOVIES", @"VIRAL CLIPS", nil]];
[_scopeControl setFrame:CGRectMake(80, 0, 200, 30)];
[_scopeControl addTarget:self
action:@selector(scopeChanged:)
forControlEvents:UIControlEventValueChanged];
[[self navigationItem] setTitleView:_scopeControl];
[_scopeControl setSelectedSegmentIndex:0];
_premiumContentViewController = [[TVPremiumContentViewController alloc] init];
_trendingContentViewController = [[TVTrendingFeedController alloc] init];
[self setScope:0];
}
- (void)scopeChanged:(id)sender {
[self setScope:self.scopeControl.selectedSegmentIndex];
}
- (void)transitionToViewController:(UIViewController *)controller
{
[self.currentViewController willMoveToParentViewController:nil];
if (controller) {
[self addChildViewController:controller];
}
controller.view.frame = self.view.bounds;
[self.view addSubview:controller.view];
[self.currentViewController.view removeFromSuperview];
[self.currentViewController removeFromParentViewController];
[controller didMoveToParentViewController:self];
self.currentViewController = controller;
}
- (void)setScope:(NSInteger)scope {
if (scope != _scope) {
_scope = scope;
UIViewController *nextController = nil;
if (_scope == 0) {
nextController = self.premiumContentViewController;
} else if (_scope == 1) {
nextController = self.trendingContentViewController;
}
[self transitionToViewController:nextController];
}
}
當我切換在TVExploreViewController分段控制,視圖的其餘部分保持白色,並沒有視圖控制器加載。任何人都知道我在做什麼錯了?
當用戶更改分段控件中選定的段時,應該調用哪些代碼?您需要將IBAction連接到UIControlEventValueChanged事件以用於分段控件,並且您根本沒有顯示任何IBAction代碼。 –
我有這個在viewDidLoad中:'[_scopeControl addTarget:自 行動:@選擇(scopeChanged :) forControlEvents:UIControlEventValueChanged]' – thisiscrazy4
@DuncanC你沒有使用Interface Builder創建控件... – John