我试图通过使用分段控制器在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的初学者,非常感谢任何帮助。
答案 0 :(得分:1)
在视图didload ....删除此行..
[contentView addSubview:segmentedControl];
[contentView2 addSubview:segmentedControl];
&安培;添加以下行......
[self.view addsubview:contentView ];
[self.view addsubview:contentView2 ];
[self.view addsubview:segmentedControl];