【问题标题】:How to change font color of UISegmentedControl如何更改 UISegmentedControl 的字体颜色
【发布时间】:2012-02-20 05:36:24
【问题描述】:

我尝试将 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 的文本颜色?

【问题讨论】:

    标签: iphone objective-c cocoa-touch uisegmentedcontrol


    【解决方案1】:

    下面是设置字体为粗体和磅值的代码:

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

    希望对你有帮助

    【讨论】:

    • 注意:此答案需要 iOS 5。
    • 这个答案不会改变主题启动者要求的字体颜色,只是字体大小。 pbibergal 的回答比较完整。
    • 这可行,但不推荐使用 UITextAttributeFont 的警告。而是使用“NSFontAttributeName”。感谢@johngraham 来自stackoverflow.com/questions/2280391/…
    【解决方案2】:
    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 及更高版本

    【讨论】:

    • 警告:您不应该保留标签。
    【解决方案3】:

    我正在使用单点触控。 不知道为什么,但是当 View 被推送时,文本颜色对我来说并没有改变。 为了解决这个问题,我只需将标签添加到段控制超级视图,然后更改它们的颜色:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 任何关于改变字体类型的想法?
      • [UIFont fontWithName:@"HelveticaNeue" size:17.0f]
      • 任何想法可能导致这不起作用?作为一个实验,我将文本颜色设置为绿色,但一切仍然是默认值(浅灰色背景上的灰色文本,或者如果突出显示蓝色背景上的白色文本。那是 iOS6。iOS7 默认为白色/清晰。)谢谢!
      • datacalculation.blogspot.in/2014/10/…给出的详细描述
      • 在 iOS 8.1 上测试,这个答案的最后一行应该从 UIControlStateHighlighted 更改为 UIControlStateSelected 以达到预期的效果。
      【解决方案5】:

      如果您需要在 iOS 7 中更改高亮段的文本颜色,这里有一个解决方案(我花了一段时间才找到,但是 thanks to this post):

      Objective-C

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

      斯威夫特

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

      【讨论】:

      • 太棒了。您可以关注datacalculation.blogspot.in/2014/10/…的详细信息
      • 这个答案终于帮我完成了对我的App的选择按钮的要求,之前包括了一种将分段控件保持在超级uiview中以使边框为正方形的方法....
      • 对于 Swift 5:var titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] UISegmentedControl.appearance().setTitleTextAttributes(titleTextAttributes, for: .normal)
      • 感谢您的帮助
      【解决方案6】:

      在 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 类参考的 Customizing Appearance 部分找到所有可能的简单自定义。

      【讨论】:

        【解决方案7】:

        以防万一帮助到达那里并正在使用 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)
        

        第二个例子,直接在segmented中,只会自定义这个segmented:

            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)
        

        【讨论】:

          【解决方案8】:

          斯威夫特 3.2:

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

          注意:如果您使用自定义背景颜色,您会在角落看到毛刺(颜色将填充外部线段..),因此请使用以下线条对其进行剪辑:

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

          【讨论】:

            【解决方案9】:

            将两种状态的字体颜色设置为黑色的代码

            斯威夫特 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)
            

            【讨论】:

            • 不适用于 iOS 13 和 Swift 5,Xcode 无法识别 segmentedControl
            • @Sky,今天只需在我的应用程序的 segmentedControl 上添加一些错误修复,此解决方案适用于 iOS 13.2 和 Swift5。
            【解决方案10】:

            为 iOS 14 和 Swift 5 更新:

            extension UISegmentedControl
            {
                func defaultConfiguration(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = UIColor.white)
                {
                    let defaultAttributes = [
                        NSAttributedString.Key.font: font,
                        NSAttributedString.Key.foregroundColor: color
                    ]
                    setTitleTextAttributes(defaultAttributes, for: .normal)
                }
            
                func selectedConfiguration(font: UIFont = UIFont.boldSystemFont(ofSize: 12), color: UIColor = UIColor.red)
                {
                    let selectedAttributes = [
                        NSAttributedString.Key.font: font,
                        NSAttributedString.Key.foregroundColor: color
                    ]
                    setTitleTextAttributes(selectedAttributes, for: .selected)
                }
            }
            

            为 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)
            

            【讨论】:

              【解决方案11】:

              在 Swift 5 中,您可以使用此语法更改颜色

              斯威夫特 5

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

              【讨论】:

                【解决方案12】:

                Swift 5 扩展

                extension UISegmentedControl {
                
                    func setTitleColor(_ color: UIColor, state: UIControl.State = .normal) {
                        var attributes = self.titleTextAttributes(for: state) ?? [:]
                        attributes[.foregroundColor] = color
                        self.setTitleTextAttributes(attributes, for: state)
                    }
                    
                    func setTitleFont(_ font: UIFont, state: UIControl.State = .normal) {
                        var attributes = self.titleTextAttributes(for: state) ?? [:]
                        attributes[.font] = font
                        self.setTitleTextAttributes(attributes, for: state)
                    }
                
                }
                

                【讨论】:

                • 按预期工作。谢谢
                猜你喜欢
                • 2012-01-15
                • 2022-01-21
                • 1970-01-01
                • 2012-10-17
                • 2016-04-17
                • 1970-01-01
                • 2016-07-28
                • 2015-05-18
                • 2011-05-20
                相关资源
                最近更新 更多