我试图通过使用分段控制器在2个uiviews之间切换,但是我似乎无法掌握它。
- (void)viewDidLoad {
[super viewDidLoad];
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
contentView = [[UIView alloc] initWithFrame:applicationFrame];
contentView.backgroundColor = [UIColor greenColor];
self.view = contentView;
CGRect applicationFrame2 = [[UIScreen mainScreen] applicationFrame];
contentView2 = [[UIView alloc] initWithFrame:applicationFrame2];
contentView2.backgroundColor = [UIColor yellowColor];
NSArray *itemArray = [NSArray arrayWithObjects: @"Player 1", @"Player 2", nil];
segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(12, 100, 350, 30);
[segmentedControl addTarget:self action:@selector(segmentAction) forControlEvents: UIControlEventValueChanged];
[contentView addSubview:segmentedControl];
[contentView2 addSubview:segmentedControl];
}
-(void) segmentAction {
if (segmentedControl.selectedSegmentIndex == 0) {
[contentView setHidden:NO];
[contentView2 setHidden:YES];
}
if (segmentedControl.selectedSegmentIndex == 1) {
[contentView setHidden:YES];
[contentView2 setHidden: NO];
}
}
当我运行此代码时,分段控件不会显示在任何视图上。我试着取出线:
[contentView2 addSubview:segmentedControl];
但是现在第二个UIView显示黑色而不是黄色,并且只有第一个UIView显示UISegmented控件。我是IOS的初学者,任何帮助将不胜感激。
最佳答案
鉴于didload ....删除此行..
[contentView addSubview:segmentedControl];
[contentView2 addSubview:segmentedControl];
并添加以下行...
[self.view addsubview:contentView ];
[self.view addsubview:contentView2 ];
[self.view addsubview:segmentedControl];
关于ios - 使用UISegmentedControl切换UIViews,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33115539/