2009-07-28 25 views
18

UISegmentedControlベースの文字列の外観をカスタマイズする方法を知っている人はいますか?私は、項目の選択状態に応じて、セルの背景色とテキストの色を別々に設定しようとしています。UISegmentedControlの色をカスタマイズする

また、カスタム文字列を含むUIImagesをオンザフライで作成する方法について知っていますか? (例えば、白い背景、オーバーレイテキスト、セグメント化されたコントロールに追加するなど)。私はあなただけのセグメント化されたコントロール内の文字列や画像を持つことができることを知っている

...

乾杯!

答えて

17

UISegmentedControlはtintColorプロパティを持っている - これはあなたがコントロールが何色に変更することができますではなく、一般的な「スタイル」(丸みを帯びた、面取り形状):上UIImagesを作成するよう

segmentedControl.tintColor = [UIColor blueColor]; 

あなたは、CGContextを作成するには、(文字列を含む)そのコンテキスト内に必要な描画を何でもして、コンテキストのCGImageの外にUIImageを得ることができ、飛ぶ:

CGContextRef drawContext = CGBitmapContextCreate(<many parameters>); 
//do drawing here 
CGImageRef finalImage = CGBitmapContextCreateImage(drawContext); 
UIImage *cellImage = [UIImage finalImage]; 
10
segmentedControl.tintColor = [UIColor colorWithRed:0.61176f green:0.61176f blue:0.61176f alpha:1.0f]; 

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
9

あなたがしなければならないすべては、次のとおりです。

// Get an array of the subviews of a UISegmentedControl, for example myUISegmentedControl: 

NSArray *arri = [myUISegmentedControl subviews]; 

// Change the tintColor of each subview within the array: 

[[arri objectAtIndex:0] setTintColor:[UIColor redColor]]; 

[[arri objectAtIndex:1] setTintColor:[UIColor greenColor]]; 
+0

のために選択されていない項目については

segcntrl.setTitleTextAttributes(titleTextAttributes, for: .normal) 

を変更したい場合は –

+1

が働いて私のために動作しません。 iOS 7で完璧に...あなたは素晴らしいです! – CommaToast

+1

良いものniceソリューション – DogCoffee

7

ここでの回答のほとんどは別の色が選択されていない状態のために要求される暗示選択された状態に基づいて、ボタンの色を設定する方法の具体的な質問に答えていません。私はかなりの時間このことに苦労し、他の人が使うために私の解決策を分かち合いたいと思っていました。

私の例では、セグメントが3つのUISegmentedControlを使用しています。すべての3つの選択されていない色は、一様な外観を与えるために同じでなければなりません。最初のセグメントと最後のセグメントの選択状態には、固有の色があります。

enter image description here

問題は、セグメント化されたコントロールを使用すると、前後に選択すると色が混ざってしまいますので、同じ順序であることが保証されていないということです。 Danはタグを使用するソリューションを投稿しましたが、残念ながらiOS 6以降で動作することは保証されていません。

このコードのほとんどは、this postから取られています。私はそれを少し変えて、独特の色を選んだ。

何それが仕事になり、ソートされますが、選択した色の設定のためにこれらの2つの重要なラインのことに注意してください:

NSInteger selectedIdx = betterSegmentedControl.selectedSegmentIndex; 
[[sortedViews objectAtIndex:selectedIdx] setTintColor:[self.segmentColors objectAtIndex:selectedIdx]]; 

- (void) updateSegmentColors 
{ 
    UIColor *checkColor = [UIColor colorWithRed: 29/255.0 green:166/255.0 blue:47/255.0 alpha:1.0]; 
    NSArray *segmentColors = [[NSArray alloc] initWithObjects:checkColor, [UIColor blueColor], [UIColor redColor], nil]; 

    UISegmentedControl *betterSegmentedControl = self.StatusControl; 

    // Get number of segments 
    NSUInteger numSegments = [betterSegmentedControl.subviews count]; 

    // Reset segment's color (non selected color) 
    for(int i = 0; i < numSegments; i++) { 
     // reset color 
     [[betterSegmentedControl.subviews objectAtIndex:i] setTintColor:nil]; 
     [[betterSegmentedControl.subviews objectAtIndex:i] setTintColor:[UIColor blueColor]]; 
    } 

    // Sort segments from left to right 
    NSArray *sortedViews = [betterSegmentedControl.subviews sortedArrayUsingFunction:compareViewsByOrigin context:NULL]; 

    // Change color of selected segment 
    NSInteger selectedIdx = betterSegmentedControl.selectedSegmentIndex; 
    [[sortedViews objectAtIndex:selectedIdx] setTintColor:[self.segmentColors objectAtIndex:selectedIdx]]; 

    // Remove all original segments from the control 
    for (id view in betterSegmentedControl.subviews) { 
     [view removeFromSuperview]; 
    } 

    // Append sorted and colored segments to the control 
    for (id view in sortedViews) { 
     [betterSegmentedControl addSubview:view]; 
    } 
} 


NSInteger static compareViewsByOrigin(id sp1, id sp2, void *context) 
{ 
    // UISegmentedControl segments use UISegment objects (private API). But we can safely cast them to UIView objects. 
    float v1 = ((UIView *)sp1).frame.origin.x; 
    float v2 = ((UIView *)sp2).frame.origin.x; 
    if (v1 < v2) 
     return NSOrderedAscending; 
    else if (v1 > v2) 
     return NSOrderedDescending; 
    else 
     return NSOrderedSame; 
} 

を、私はので、それ自身のメソッド内のコードを配置私はこれらのセグメント化されたコントロールをテーブルビューで読み込み、ロード時に(ストレージからの既存の状態)、ユーザーが選択を変更したときにそれを実行する必要があります。今何かが変わったときに[Self updateSegmentColors];に電話するだけです。

1

私はXCode 6のInterface Builderを使用してそれを実行できました。色合いプロパティを添付:

enter image description here

6

私はこのような何かを行うのを発見した最良の方法は、セグメント化されたコントロール上の異なるUIControlStatesための異なる属性を設定しています。ここで

self.segmentedControl.tintColor = [UIColor cb_Grey1Color]; 
self.segmentedControl.backgroundColor = [UIColor cb_Grey3Color]; 
NSDictionary *selectedAttributes = [NSDictionary dictionaryWithObjectsAndKeys: 
            [UIFont cbGothamBookFontWithSize:13.0], NSFontAttributeName, 
            [UIColor whiteColor], NSForegroundColorAttributeName, 
            [UIColor cb_Grey1Color], NSBackgroundColorAttributeName, nil]; 
[self.segmentedControl setTitleTextAttributes:selectedAttributes forState:UIControlStateSelected]; 
NSDictionary *unselectedAttributes = [NSDictionary dictionaryWithObjectsAndKeys: 
             [UIFont cbGothamBookFontWithSize:13.0], NSFontAttributeName, 
             [UIColor cb_Grey2Color], NSForegroundColorAttributeName, 
             [UIColor cb_Grey3Color], NSBackgroundColorAttributeName, nil]; 
[self.segmentedControl setTitleTextAttributes:unselectedAttributes forState:UIControlStateNormal]; 
+0

BackgroundColorAttributeはタイトルの背景を変更するだけです –

2

iOS9で動作するサンプルコードですが、それはハックされ、以降のバージョンでは動作しない可能性があります:

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"Title1", @"Title2"]]; 
for (id segment in [segmentedControl subviews]) 
{ 
    for (id view in [segment subviews]) 
    { 
     NSString *desc = [view description]; 
     if ([desc containsString:@"UISegmentLabel"]) 
     { 
      [segment setTintColor:([desc containsString:@"Title1"] ? [UIColor blueColor] : [UIColor greenColor])]; 
     } 
    } 
} 
0

私は似たような達成したかった - の背景色を設定選択されたセグメントを1つの色に変換し、残りのセグメントの「輪郭」は異なる色にする。

UISegmentedControlをサブクラス化し、2つのメソッドをオーバーライドして初期状態のスタイルを設定し、changeイベントをキャプチャしてユーザーが別のセグメントを選択すると自動的にスタイルを設定することを考えています。

- (void)layoutSubviews { 
    [super layoutSubviews]; 
    [self updateSegmentColors]; 
} 
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    [super touchesEnded:touches withEvent:event]; 
    [self updateSegmentColors]; 
} 
- (void)updateSegmentColors { 
    NSArray* segments = [self.subviews sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { 
     // UISegmentedControl segments use UISegment objects (private API). But we can safely cast them to UIView objects. 
     float v1 = ((UIView *)obj1).frame.origin.x; 
     float v2 = ((UIView *)obj2).frame.origin.x; 
     if (v1 < v2) return NSOrderedAscending; 
     else if (v1 > v2) return NSOrderedDescending; 
     else return NSOrderedSame; 
    }]; 
    for (int i=0; i<segments.count; i++) { 
     if (i == self.selectedSegmentIndex) { 
      [segments[i] setTintColor:[UIColor redColor]]; 
     } else { 
      [segments[i] setTintColor:[UIColor grayColor]]; 
     } 
    } 
} 
0

フォントの色SWIFT 3及び迅速な4選択した項目

segcntrl.setTitleTextAttributes(titleTextAttributes, for: .selected) 
関連する問題