2009-07-28 60 views
18

有誰知道一種方法來定製基於UISegmentedControl的字符串的外觀嗎?我試圖根據項目的選定狀態設置單元格的背景顏色和文本顏色。定製UISegmentedControl的顏色

另外,你知道一種方法來創建UIImages在飛行中包括自定義字符串? (例如創建具有白色背景的uiimage,覆蓋文本,添加到分段控件)。

我知道,你只能在分段控制字符串或圖片...

乾杯!

回答

17

UISegmentedControl有一個tintColor屬性 - 這允許您更改控制是什麼顏色,但不是一般的「樣式」(圓角,斜面形狀):

segmentedControl.tintColor = [UIColor blueColor]; 

至於在創建UIImages飛,你可以創建一個CGContext上,做任何繪圖時,需要在這方面(包括字符串),然後得到一個UIImage了上下文的CGImage的:

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

對我不起作用 – 2013-06-05 12:26:30

+1

曾任職在iOS 7上完美...你真了不起! – CommaToast 2013-10-08 15:43:57

7

這裏的大多數答案不回答瞭如何基於這意味着另一種顏色需要爲未選中狀態選中狀態設置按鈕顏色的具體問題。我爲此奮鬥了很長一段時間,並希望分享我的解決方案供其他人使用。

我的示例使用帶有三段的UISegmentedControl。所有三種顏色的未選顏色應該相同,以使其具有統一的外觀。第一個和最後一個段的選定狀態具有唯一的顏色。

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]; 
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

我想要完成類似的東西 - 設置背景顏色選定的片段爲一種顏色,而其餘片段的「輪廓」爲不同的顏色。

借鑑波特蘭亞軍的答案,這個想法是UISegmentedControl的子類,並覆蓋2種方法既可以設置初始狀態,也可以捕獲更改事件,以便在用戶選擇不同的段時自動進行設置。

- (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

字體顏色迅速3,迅速4,如果你想改變

,未被選定項目

segcntrl.setTitleTextAttributes(titleTextAttributes, for: .normal) 

對於所選擇的項目

segcntrl.setTitleTextAttributes(titleTextAttributes, for: .selected) 
相關問題