UISegmentController和UIViews

时间:2013-02-25 04:23:52

标签: iphone ios objective-c uisegmentedcontrol

我想知道如何通过UISegmentController正确操作两个视图。

现在我有两个UIViewsUISegmentController以及过程 changeView

- (void)changeView:(NSInteger)index {
switch (index) {
    case 0:
        self.recipeInfoView.alpha = 1;
        self.recipeInfoView2.alpha = 0;
        break;
    case 1:
        self.recipeInfoView.alpha = 0;
        self.recipeInfoView2.alpha = 1;
        break;

    default:
        break;
}

此代码有效,但每个视图的位置和大小都相同,并且使用起来非常不舒服。 我正在使用故事板。

2 个答案:

答案 0 :(得分:3)

首先编写以下代码用于创建UISegmentedControl并为您提供UIView的颜色。

- (void)viewDidLoad
{
    [super viewDidLoad];

   //Make hide of your UIView 
       self.recipeInfoView.hide = YES;
       self.recipeInfoView2.hide = YES;

  //Give color of your UIView
       self.recipeInfoView.backgroundColor = [UIColor redColor];
       self.recipeInfoView.backgroundColor = [UIColor blackColor];

  //Create UISegmentedControl Controller 
    NSArray *itemArray = [NSArray arrayWithObjects: @"FirstView", @"SecondView", nil];
    self.segmentedControl= [[UISegmentedControl alloc] initWithItems:itemArray];
    self.segmentedControl.frame = CGRectMake(35, 100, 250, 33);
    self.segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    self.segmentedControl.momentary=NO;
    self.segmentedControl.tintColor=[UIColor darkGrayColor];

    [self.segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:self.segmentedControl];

}

// segmentAction方法

- (IBAction)segmentAction:(id)sender
{
    if([sender selectedSegmentIndex] == 0)
    {
       if(self.recipeInfoView.isHidden == YES)
          self.recipeInfoView.Hidden == NO;
      else
          self.recipeInfoView.Hidden == NO;

      if(self.recipeInfoView2.isHidden == YES)
           self.recipeInfoView2.Hidden == YES;
      else
           self.recipeInfoView2.Hidden == YES;

   }
   else if([sender selectedSegmentIndex] == 1)
   {
       if(self.recipeInfoView2.isHidden == YES)
           self.recipeInfoView2.Hidden == NO;
       else
           self.recipeInfoView2.Hidden == NO;

       if(self.recipeInfoView.isHidden == YES)
            self.recipeInfoView.Hidden == YES;
       else
           self.recipeInfoView.Hidden == YES; 

    }
}

此代码可能对您的情况有所帮助。

答案 1 :(得分:1)

设置视图属性hidden = YES或NO,而不是为视图设置alpha