これを行うには、たとえば、セグメント化されたコントロールのサブビューを繰り返し処理してisSelectedプロパティをテストし、setTintColor:そのサブビューでメソッドを呼び出すなどして、選択したセグメントを見つける必要があります。
私はこれを、Interface BuilderのValueChangedイベントの各セグメント化されたコントロールにアクションを接続することによって行いました。これらを、本質的にmspragueの答えであるビューコントローラーファイルのこのメソッドに接続しました。
- (IBAction)segmentedControlValueChanged:(UISegmentedControl*)sender
{
for (int i=0; i<[sender.subviews count]; i++)
{
if ([[sender.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && [[sender.subviews objectAtIndex:i]isSelected])
{
[[sender.subviews objectAtIndex:i] setTintColor:[UIColor whiteColor]];
}
if ([[sender.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && ![[sender.subviews objectAtIndex:i] isSelected])
{
[[sender.subviews objectAtIndex:i] setTintColor:[UIColor blackColor]];
}
}
}
ユーザーがビューを開くたびにコントロールが正しく表示されるようにするには、メソッドをオーバーライドして-(void)viewDidAppear:animated、次のようにメソッドを呼び出す必要もあります。
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
//Ensure the segmented controls are properly highlighted
[self segmentedControlValueChanged:segmentedControlOne];
[self segmentedControlValueChanged:segmentedControlTwo];
}
一部のボーナスポイントでは、選択時に白の色合いを使用するようにセグメント化されたコントロールを設定したい場合は、選択時にテキストの色を黒に変更することもできます。次のように行うことができます。
//Create a dictionary to hold the new text attributes
NSMutableDictionary * textAttributes = [[NSMutableDictionary alloc] init];
//Add an entry to set the text to black
[textAttributes setObject:[UIColor blackColor] forKey:UITextAttributeTextColor];
//Set the attributes on the desired control but only for the selected state
[segmentedControlOne setTitleTextAttributes:textAttributes forState:UIControlStateSelected];
iOS 6の導入により、viewDidAppearメソッドで選択したアイテムの色合いの色を初めて設定しても機能しません。これを回避するために、グランドセントラルディスパッチを使用して、次のように1秒後に選択した色を変更しました。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.05 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self segmentedControlValueChanged:segmentedControlOne];
});