用于UISegments的UISegmentedControl setTint仅在单击后才有效

时间:2013-01-28 22:04:53

标签: xcode ios6 uisegmentedcontrol uicolor tint

Xcode,Obj-c, iOS 5.2 iOS 6.0

我有一个UISegmentedControl,它使用以下内容插入底部工具栏:

-(void) makeSegmentedControl {
    self.SegControl = [[UISegmentedControl alloc] initWithItems:@[@"Title1",@"Title2"]];
    self.SegControl.segmentedControlStyle = UISegmentedControlStyleBar;
    [self.SegControl setTarget:self action:@selector(handleSegment) forControlEvents:UIControlEventValueChanged]
    [self.SegControl setSelectedSegmentIndex:0];
 }
 -(void) AddSegmentedControlToToolbar {
     UIBarButtonItem *tmp = [UIBarButtonItem new];
     [tmp setCustomView:self.SegControl];
     [self.navigationController.toolbar setItems@[tmp]];
 }
 -(void) tintSegmentedControl {
     for (int i = 0; i< [self.SegControl.subviews count]; i++) {
          [[self.SegControl.subviews objectAtIndex:i] setTint:[UIcolor greenColor];
      }
      NSArray * sortedViews = [self.SegControl.subviews sortArrayUsingFunction:sortFunction];
      [[sortedViews objectAtIndex:self.SegControl.selectedSegmentIndex] setTintColor:[UIColor lightGreenColor]];
      for (id view in self.SegControl.subviews) {
          [view removeFromSuperView];
      }
      for (id view in sortedViews) {
          [self.SegControl addSubview:view];
      }
 }
 -(void)viewDidLoad {
     [self makeSegmentedControl];
     [self addSegmentedControlToToobar];
     [self tintSegmentedControl];
  } 
  -(void) handleSegment {
      [self tintSegmentedControl];
  }

当我在我们的应用程序中运行类似的代码时,它显示了一个非常蓝色的UISegmentedController,它在点击时变为绿色。我尝试了一些事情,似乎UISegments上的色调只是在视图加载完毕后才会拒绝。知道这里发生了什么吗?

修改

所以,事实证明我实际上正在使用iOS 6.0模拟器,并且在iOS 6中存在一个限制,你可以在ViewDidAppear:Animated:运行之前对UISegmentedController进行着色。我认为这是问题所在,因为当我做出这个改变时:

-(void)viewDidLoad {
     [self makeSegmentedControl];
     [self addSegmentedControlToToobar];
} 
-(void)viewDidAppear {
     [NSTimer timerWithTimeInterval:0 target:self selector:@selector(tintSegmentedControl) userInfo:nil repeats:NO];
}

它有效。不是100%确定发生了什么。有没有更简单的方法?

2 个答案:

答案 0 :(得分:1)

试试这段代码

-(void) tintSegmentedControl {
    [self.SegControl setTintColor:[UIColor greenColor];
      NSArray * sortedViews = [self.SegControl.subviews sortArrayUsingFunction:sortFunction];
      [[sortedViews objectAtIndex:self.SegControl.selectedSegmentIndex] setTintColor:[UIColor lightGreenColor]];
      for (id view in self.SegControl.subviews) {
          [view removeFromSuperView];
      }
      for (id view in sortedViews) {
          [self.SegControl addSubview:view];
      }
 }

答案 1 :(得分:0)

因此,事实证明iOS 6中存在一个限制,即在ViewDidAppear:Animated:has run之前,你无法对UISegmentedController进行着色。为了规避它,我改变了代码(正如你在编辑中看到的那样)。

-(void)viewDidLoad {
     [self makeSegmentedControl];
     [self addSegmentedControlToToobar];
} 
-(void)viewDidAppear {
     [NSTimer timerWithTimeInterval:0 target:self selector:@selector(tintSegmentedControl) userInfo:nil repeats:NO];
}