ProgramingTip

UISegmentedControl의 글꼴 색상을 변경하는 방법

bestdevel 2020. 12. 9. 21:33
반응형

UISegmentedControl의 글꼴 색상을 변경하는 방법


UISegmentedControl(iOS 4. *의 경우) 글꼴 색상을 흰색에서 검정색으로 변경합니다.

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

그러나 텍스트 색상은 변경되지 않습니다. 텍스트 색상을 변경해야 UISegmentedControl합니까?


iOS 6.0 이상에서는 매우 간단합니다.

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

iOS 7에서 강조하는 세그먼트의 텍스트 색상을 변경해야하는 경우 여기에 해결이 있습니다 (찾는 데 시간이 걸렸지만이 게시물 덕분에 ).

목표 -C

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

빠른

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

다음은 글꼴을 굵은 글꼴과 포인트 크기로 설정하는 코드입니다.

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

도움이 되길 바랍니다


두 상태 글꼴 색상을 검은 색으로 설정하는 코드

스위프트 5

    let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .normal)
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .selected)

스위프트 4

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

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

iOS 3.0 이상


Swift 4 업데이트-이 확장을 사용하십시오 (확장은 항상 굉장하기 때문입니다 .. !!)

extension UISegmentedControl {

func defaultConfiguration(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = UIColor.gray) {
    let defaultAttributes = [
        NSAttributedStringKey.font.rawValue: font,
        NSAttributedStringKey.foregroundColor.rawValue: color
    ]
    setTitleTextAttributes(defaultAttributes, for: .normal)
}

func selectedConfiguration(font: UIFont = UIFont.boldSystemFont(ofSize: 12), color: UIColor = UIColor.red) {
    let selectedAttributes = [
        NSAttributedStringKey.font.rawValue: font,
        NSAttributedStringKey.foregroundColor.rawValue: color
    ]
    setTitleTextAttributes(selectedAttributes, for: .selected)
}
}

각 클래스에서 기능을 사용할 수 있습니다.

@IBOutlet weak var segment: UISegmentedControl!

segment.defaultConfiguration()
// or provide paramater as per your requirement
segment.selectedConfiguration(color: .blue)


swift를 사용하여 작업하는 다른 사람을 돕기 위해.

가능한 두 가지 방법을 설명하겠습니다. UIAppearance작업중 인 세그먼트에서 또는 직접 텍스트 속성을 사용 가능 합니다.

모양의 속성을 설정하는 첫 번째 예제는 앱의 모든 세그먼트 컨트롤을 사용자 지정합니다.

    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)

두 번째 예는 세그먼트별로 직접 구성 완료이 세그먼트 만 맞춤 설정합니다.

    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)

신속한 3.2 :

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

참고 : 사용자 정의 배경색을 사용하는 경우 모서리에 결함이 표시됩니다 (색상이 외부 세그먼트를 채 ..), 다음 선을 사용하여 잘라냅니다.

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

iOS 5.0 이상에서는 titleTextAttributes를 사용하여 UISegmentedControl개체 를 사용자 수 있습니다.

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

여기서는 각 상태에 대한 사용자 정의 글꼴, 글꼴 크기, 색상으로 글꼴을 설정합니다 UISegmentedControl.

UISegmentedControl Class Reference Customizing Appearance 섹션 에서 가능한 모든 간단한 사용자 지정을 찾을 수 있습니다 .


Im monotouch를 사용하고 있습니다. 이유는 모르지만 View를 눌렀을 때 텍스트 색상이 변경되지 않았습니다. 이 문제를 해결하려면 세그먼트 제어 superview에 레이블을 추가 한 다음 색상을 변경하십시오.

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

그리고 그것을 사용하십시오

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

Swift 5에서는이 구문으로 색상을 변경할 수 있습니다.

스위프트 5

let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]
groupSegment.setTitleTextAttributes(titleTextAttributes, for: .selected)

참고 URL : https://stackoverflow.com/questions/9029760/how-to-change-font-color-of-uisegmentedcontrol

반응형