2012-01-27 15 views
45

próbuję zmienić kolor czcionki z białego na czarny dla UISegmentedControl (na iOS 4. *)Jak zmienić kolor czcionki z UISegmentedControl

UISegmentedControl *button = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:itemTitle, nil]] autorelease]; 
button.momentary = YES; 
button.segmentedControlStyle = UISegmentedControlStyleBar; 
button.tintColor = [UIColor redColor];  
for (id segment in [button subviews]) { 
    for (id label in [segment subviews]) { 
     if ([label isKindOfClass:[UILabel class]]) { 
      UILabel *titleLabel = (UILabel *) label; 
      [titleLabel setTextColor:[UIColor blackColor]]; 
     } 
    } 
} 
UIBarButtonItem *barButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease]; 

Ale kolor tekstu nie zmieniło. Co powinienem zrobić, aby zmienić kolor tekstu na UISegmentedControl?

Odpowiedz

28

Poniżej znajduje się kod, aby ustawić czcionkę na pogrubioną czcionką i pkt rozmiarze:

UIFont *Boldfont = [UIFont boldSystemFontOfSize:12.0f]; 
NSDictionary *attributes = [NSDictionary dictionaryWithObject:Boldfont 
                 forKey: NSFontAttributeName]; 
[segmentedControl setTitleTextAttributes:attributes 
           forState:UIControlStateNormal]; 

Mam nadzieję, że to pomaga

+4

Uwaga: ta odpowiedź wymaga iOS 5. – Costique

+1

Ta odpowiedź nie zmienia koloru czcionki, gdy żądany rozrusznik tematu, tylko rozmiar czcionki. Odpowiedź pbibergala jest bardziej kompletna. –

+0

To działa, ale nadchodzi ostrzeżenie, ponieważ UITextAttributeFont jest przestarzałe. Zamiast tego użyj "NSFontAttributeName". Wszystko dzięki @johngraham z http://stackoverflow.com/questions/2280391/change-font-size-of-uisegmentedcontrol – mavericks

7
for (UIView *v in [[[segment subviews] objectAtIndex:0] subviews]) { 
    if ([v isKindOfClass:[UILabel class]]) { 
     UILabel *label=(UILabel *)[v retain]; 
     lable.textColor=[UIColor blackColor]; 
    } 
} 

dla iOS 3.0 i powyżej

+5

Ostrzeżenie: nie powinieneś przechowywać etykiety. – Costique

+0

Nie działa na iOS 6 – CommaToast

+0

Również Nie działa na iOS 10 –

1

im przy MonoTouch . Nie wiem dlaczego, ale kiedy widok został wypchnięty kolor tekstu nie zmienił się dla mnie. dla rozwiązania tego im tylko dodać etykiety do sterowania segmentu SuperView a następnie zmienić ich kolory:

public static void SetColoredTittles(this UISegmentedControl s, string[] titles, UIColor selected, UIColor notSelected) 
{ 
    var segmentedLabels = new List<UILabel>(); 
    float width = s.Frame.Width/titles.Length; 

    for (int i = 0; i < titles.Length; i++) 
    { 
     var frame = new RectangleF(s.Frame.X + i*width, s.Frame.Y, width,s.Frame.Height); 
     UILabel label = new UILabel(frame); 
     label.TextAlignment = UITextAlignment.Center; 
     label.BackgroundColor = UIColor.Clear; 
     label.Font = UIFont.BoldSystemFontOfSize(12f); 
     label.Text = titles[i]; 
     s.Superview.AddSubview(label); 
     segmentedLabels.Add(label); 
    } 

    s.ValueChanged += delegate 
    { 
     TextColorChange(s,segmentedLabels, selected, notSelected); 
    }; 
    TextColorChange(s,segmentedLabels, selected, notSelected); 
} 

static void TextColorChange(UISegmentedControl s, List<UILabel> segmentedLabels, UIColor selected, UIColor notSelected) 
{ 
    for (int i = 0; i < segmentedLabels.Count; i++) 
    { 
     if(i == s.SelectedSegment) segmentedLabels[i].TextColor = selected; 
     else segmentedLabels[i].TextColor = notSelected; 
    } 
} 

a następnie używać go

segmented.SetColoredTittles(new string[] { 
      "text1", 
      "text2", 
      "text3" 
     }, UIColor.White,UIColor.DarkGray); 
107

w iOS 6.0 i powyżej niego jest bardzo proste:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: 
          [UIFont boldSystemFontOfSize:17], NSFontAttributeName, 
          [UIColor blackColor], NSForegroundColorAttributeName, 
          nil]; 
[_segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal]; 
NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName]; 
[_segmentedControl setTitleTextAttributes:highlightedAttributes forState:UIControlStateSelected]; 
+0

żadnego pomysłu na temat zmiany rodzaju czcionki? –

+0

'[UIFont fontWithName: @" HelveticaNeue "size: 17.0f]' – pbibergal

+0

Jakieś pomysły, które mogą spowodować, że to nie zadziała? W trakcie eksperymentu ustawiam kolor tekstu na zielony, ale wszystko jest nadal domyślne (szary tekst na jasnoszarym tle lub biały tekst na niebieskim tle, jeśli jest podświetlony, to iOS6. IOS7 jest domyślnie biały/jasny.) Dzięki! – Olie

57

Jeśli chcesz zmienić kolor tekstu zaznaczonego segmentu w iOS 7, oto rozwiązanie (trochę czasu zajęło mi znalezienie, ale thanks to this post):

Objective-C

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]} forState:UIControlStateSelected]; 

Swift

let titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] 
    UISegmentedControl.appearance().setTitleTextAttributes(titleTextAttributes, forState: .Selected) 
+0

Świetnie. Możesz śledzić szczegółowe informacje na http://datacalculation.blogspot.in/2014/10/how-to-change-uisegmentedcontrol-text.html –

+2

Edytuję twoją dobrą odpowiedź, aby dodać szybki kod –

+0

Ta odpowiedź w końcu pomogła mi ukończyć wymagania dotyczące przycisku wyboru w mojej aplikacji, poprzednio obejmującego sposób na utrzymanie segmentowej kontroli w super uiview, aby kwadratura była ... –

2

w iOS 5.0 i później można użyć titleTextAttributes dostosować UISegmentedControl obiekty:

NSDictionary *segmentedControlTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:18.0], NSForegroundColorAttributeName:[UIColor whiteColor]}; 
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateNormal]; 
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateHighlighted]; 
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateSelected]; 

Tutaj ustawić fon t do niestandardowej czcionki, rozmiaru czcionki, koloru dla każdego stanu urządzenia UISegmentedControl.

Znajdziesz wszystkie możliwe proste dostosowania w sekcji Customizing Appearance odniesienia klasy UISegmentedControl.

4

Na wszelki wypadek, aby pomóc komuś innemu, kto tam dotrze i pracuje szybko.

Podam dwa możliwe sposoby robienia tego. Możesz zmienić atrybuty tekstu w UIAppearance lub bezpośrednio w segmentowanym, który działa.

Pierwszy przykład ustawienie atrybuty w wyglądzie, w ten sposób można dostosować wszystkie segmentowane kontroli w aplikacji:

let attributes = [ NSForegroundColorAttributeName : UIColor.grayColor(), 
     NSFontAttributeName : UIFont.systemFontOfSize(20)]; 
    let attributesSelected = [ NSForegroundColorAttributeName : UIColor.blueColor(), 
     NSFontAttributeName : UIFont.systemFontOfSize(20)]; 
    UISegmentedControl.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal) 
    UISegmentedControl.appearance().setTitleTextAttributes(attributesSelected, forState: UIControlState.Selected) 

Drugi przykład, bezpośrednio w segmentacji, dostosuje tylko ten segmentacji:

let attributes = [ NSForegroundColorAttributeName : UIColor.grayColor(), 
     NSFontAttributeName : UIFont.systemFontOfSize(20)]; 
    let attributesSelected = [ NSForegroundColorAttributeName : UIColor.blueColor(), 
     NSFontAttributeName : UIFont.systemFontOfSize(20)]; 
    segmented.setTitleTextAttributes(attributes, forState: UIControlState.Normal) 
    segmented.setTitleTextAttributes(attributesSelected, forState: UIControlState.Selected) 
4

Swift 3.2:

let attributes = [ 
          NSFontAttributeName : bigTextFont, 
          NSForegroundColorAttributeName : UIColor.blue, 
          ]   
segmentedControl?.setTitleTextAttributes(attributes, for: .normal) 

uwaga: f użyć niestandardowy kolor tła, widać glitch w narożnikach (kolor wypełni segmenty poza ..), więc korzystać z tych linii, aby go Filmu:

segmentedControl!.layer.cornerRadius = 4.0 
segmentedControl!.clipsToBounds = true 
1

Swift 4 kod, aby ustawić kolor czcionki obu państw do czarny

let titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black] 
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .normal) 
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .selected) 
Powiązane problemy