如何在 iOS 13 中更改 UISegmentedControl 中的段的颜色?

How to change the colors of a segment in a UISegmentedControl in iOS 13?

UISegmentedControl 在 iOS 13 中有了新的外观,并且现有的用于更改分段控件颜色的代码不再像以前那样工作。

在 iOS 13 之前,您可以设置 tintColor,这将用于分段控件周围的边框、分段之间的线条以及所选分段的背景颜色。然后,您可以使用 titleTextAttributes.

的前景色属性更改每个片段标题的颜色

在 iOS 13 下,tintColor 什么都不做。可以设置分段控件的backgroundColor来改变分段控件的整体颜色。但是我找不到任何方法来改变用作所选片段背景的颜色。设置文本属性仍然有效。我什至尝试设置标题的背景颜色,但这只会影响标题的背景,不会影响所选片段的其余部分的背景颜色。

总之,如何修改iOS13中aUISegmentedControl当前选中段的背景色?有没有合适的解决方案,使用 public API,不需要深入研究私有子视图结构?

iOS 13 中没有新属性,因为 UISegmentedControlUIControl 和 none UIView 中的更改是相关的。

截至 Xcode 11 测试版 3

There is now the selectedSegmentTintColor property on UISegmentedControl.


找回iOS12外观

我无法为所选片段着色,希望它会在即将推出的测试版中得到修复。

如果不设置正常状态的背景图片(移除所有 iOS 13 样式),则设置选中状态的背景图片不起作用

但我能够将它恢复到 iOS 12 的外观(或足够接近,我无法将角半径 return 变小)。

这并不理想,但亮白色的分段控件在我们的应用程序中看起来有点格格不入。

(没有意识到 UIImage(color:) 是我们代码库中的扩展方法。但是实现它的代码在网络上)

extension UISegmentedControl {
    /// Tint color doesn't have any effect on iOS 13.
    func ensureiOS12Style() {
        if #available(iOS 13, *) {
            let tintColorImage = UIImage(color: tintColor)
            // Must set the background image for normal to something (even clear) else the rest won't work
            setBackgroundImage(UIImage(color: backgroundColor ?? .clear), for: .normal, barMetrics: .default)
            setBackgroundImage(tintColorImage, for: .selected, barMetrics: .default)
            setBackgroundImage(UIImage(color: tintColor.withAlphaComponent(0.2)), for: .highlighted, barMetrics: .default)
            setBackgroundImage(tintColorImage, for: [.highlighted, .selected], barMetrics: .default)
            setTitleTextAttributes([.foregroundColor: tintColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .normal)
            setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
            layer.borderWidth = 1
            layer.borderColor = tintColor.cgColor
        }
    }
}

我已经尝试了解决方法,对我来说效果很好。这是 Objective-C 版本:

@interface UISegmentedControl (Common)
- (void)ensureiOS12Style;
@end
@implementation UISegmentedControl (Common)
- (void)ensureiOS12Style {
    // UISegmentedControl has changed in iOS 13 and setting the tint
    // color now has no effect.
    if (@available(iOS 13, *)) {
        UIColor *tintColor = [self tintColor];
        UIImage *tintColorImage = [self imageWithColor:tintColor];
        // Must set the background image for normal to something (even clear) else the rest won't work
        [self setBackgroundImage:[self imageWithColor:self.backgroundColor ? self.backgroundColor : [UIColor clearColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        [self setBackgroundImage:tintColorImage forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
        [self setBackgroundImage:[self imageWithColor:[tintColor colorWithAlphaComponent:0.2]] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
        [self setBackgroundImage:tintColorImage forState:UIControlStateSelected|UIControlStateSelected barMetrics:UIBarMetricsDefault];
        [self setTitleTextAttributes:@{NSForegroundColorAttributeName: tintColor, NSFontAttributeName: [UIFont systemFontOfSize:13]} forState:UIControlStateNormal];
        [self setDividerImage:tintColorImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        self.layer.borderWidth = 1;
        self.layer.borderColor = [tintColor CGColor];
    }
}

- (UIImage *)imageWithColor: (UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
@end

截至 Xcode 11 测试版 3

There is now the selectedSegmentTintColor property on UISegmentedControl.

谢谢@rmaddy!


原始答案,针对 Xcode 11 beta 和 beta 2

Is there a proper solution, using public APIs, that doesn't require digging into the private subview structure?

使用Xcode 11.0 beta,做起来似乎是一个挑战by-the-rules,因为它基本上需要自己重绘每个状态的所有背景图像,圆角,透明度和 resizableImage(withCapInsets:)。例如,您需要生成类似于以下内容的彩色图像:

所以现在,let's-dig-into-the-subviews 方法似乎容易得多:

class TintedSegmentedControl: UISegmentedControl {

    override func layoutSubviews() {
        super.layoutSubviews()

        if #available(iOS 13.0, *) {
            for subview in subviews {
                if let selectedImageView = subview.subviews.last(where: { [=10=] is UIImageView }) as? UIImageView,
                    let image = selectedImageView.image {
                    selectedImageView.image = image.withRenderingMode(.alwaysTemplate)
                    break
                }
            }
        }
    }
}

此解决方案会正确地将色调颜色应用到选区,如下所示:

这是我对 Jonathan. 对 Xamarin.iOS (C#) 的回答的看法,但修复了图像大小问题。正如 Coeur 对 Colin Blake 的回答的评论一样,我将除分隔线之外的所有图像都设为分段控件的大小。分隔符是段的 1x 高度。

public static UIImage ImageWithColor(UIColor color, CGSize size)
{
    var rect = new CGRect(0, 0, size.Width, size.Height);
    UIGraphics.BeginImageContext(rect.Size);
    var context = UIGraphics.GetCurrentContext();
    context.SetFillColor(color.CGColor);
    context.FillRect(rect);
    var image = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();
    return image;
}

// 
public static void ColorSegmentiOS13(UISegmentedControl uis, UIColor tintColor, UIColor textSelectedColor, UIColor textDeselectedColor)
{
    if (!UIDevice.CurrentDevice.CheckSystemVersion(13, 0))
    {
        return;
    }

    UIImage image(UIColor color)
    {
        return ImageWithColor(color, uis.Frame.Size);
    }

    UIImage imageDivider(UIColor color)
    {
        return ImageWithColor(color, 1, uis.Frame.Height);
    }

    // Must set the background image for normal to something (even clear) else the rest won't work
    //setBackgroundImage(UIImage(color: backgroundColor ?? .clear), for: .normal, barMetrics: .default)
    uis.SetBackgroundImage(image(UIColor.Clear), UIControlState.Normal, UIBarMetrics.Default);

    // setBackgroundImage(tintColorImage, for: .selected, barMetrics: .default)
    uis.SetBackgroundImage(image(tintColor), UIControlState.Selected, UIBarMetrics.Default);

    // setBackgroundImage(UIImage(color: tintColor.withAlphaComponent(0.2)), for: .highlighted, barMetrics: .default)
    uis.SetBackgroundImage(image(tintColor.ColorWithAlpha(0.2f)), UIControlState.Highlighted, UIBarMetrics.Default);

    // setBackgroundImage(tintColorImage, for: [.highlighted, .selected], barMetrics: .default)
    uis.SetBackgroundImage(image(tintColor), UIControlState.Highlighted | UIControlState.Selected, UIBarMetrics.Default);

    // setTitleTextAttributes([.foregroundColor: tintColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .normal)
    // Change: support distinct color for selected/de-selected; keep original font
    uis.SetTitleTextAttributes(new UITextAttributes() { TextColor = textDeselectedColor }, UIControlState.Normal); //Font = UIFont.SystemFontOfSize(13, UIFontWeight.Regular)
    uis.SetTitleTextAttributes(new UITextAttributes() { TextColor = textSelectedColor, }, UIControlState.Selected); //Font = UIFont.SystemFontOfSize(13, UIFontWeight.Regular)

    // setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
    uis.SetDividerImage(imageDivider(tintColor), UIControlState.Normal, UIControlState.Normal, UIBarMetrics.Default);

    //layer.borderWidth = 1
    uis.Layer.BorderWidth = 1;

    //layer.borderColor = tintColor.cgColor
    uis.Layer.BorderColor = tintColor.CGColor;
}

从 iOS 13b3 开始,现在 UISegmentedControl 上有一个 selectedSegmentTintColor

要更改分段控件的整体颜色,请使用其 backgroundColor

要更改所选线段的颜色,请使用 selectedSegmentTintColor

要更改未选择的片段标题的 color/font,请使用状态为 .normal/UIControlStateNormalsetTitleTextAttributes

要更改所选片段标题的 color/font,请使用状态为 .selected/UIControlStateSelectedsetTitleTextAttributes

如果您使用图像创建分段控件,如果图像创建为模板图像,则分段控件的 tintColor 将用于为图像着色。但这有一个问题。如果您将 tintColor 设置为与 selectedSegmentTintColor 相同的颜色,则图像将不会在所选片段中可见。如果您将 tintColor 设置为与 backgroundColor 相同的颜色,则未选中片段上的图像将不可见。这意味着您的带图像的分段控件必须使用 3 种不同的颜色才能使所有内容可见。或者您可以使用 non-template 图像而不设置 tintColor.

在 iOS 12 或更早版本下,只需设置分段控件的 tintColor 或依赖应用的整体色调。

if (@available(iOS 13.0, *)) {

    [self.segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName: [UIFont systemFontOfSize:13]} forState:UIControlStateSelected];
    [self.segmentedControl setSelectedSegmentTintColor:[UIColor blueColor]];

} else {

[self.segmentedControl setTintColor:[UIColor blueColor]];}

您可以实现以下方法

extension UISegmentedControl{
    func selectedSegmentTintColor(_ color: UIColor) {
        self.setTitleTextAttributes([.foregroundColor: color], for: .selected)
    }
    func unselectedSegmentTintColor(_ color: UIColor) {
        self.setTitleTextAttributes([.foregroundColor: color], for: .normal)
    }
}

使用代码

segmentControl.unselectedSegmentTintColor(.white)
segmentControl.selectedSegmentTintColor(.black)

Swift @Ilahi Charfeddine 的回答版本:

if #available(iOS 13.0, *) {
   segmentedControl.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
   segmentedControl.selectedSegmentTintColor = UIColor.blue
} else {
   segmentedControl.tintColor = UIColor.blue
}

iOS13 UISegmentController

使用方法:

segment.setOldLayout(tintColor: .green)

extension UISegmentedControl
{
    func setOldLayout(tintColor: UIColor)
    {
        if #available(iOS 13, *)
        {
            let bg = UIImage(color: .clear, size: CGSize(width: 1, height: 32))
             let devider = UIImage(color: tintColor, size: CGSize(width: 1, height: 32))

             //set background images
             self.setBackgroundImage(bg, for: .normal, barMetrics: .default)
             self.setBackgroundImage(devider, for: .selected, barMetrics: .default)

             //set divider color
             self.setDividerImage(devider, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)

             //set border
             self.layer.borderWidth = 1
             self.layer.borderColor = tintColor.cgColor

             //set label color
             self.setTitleTextAttributes([.foregroundColor: tintColor], for: .normal)
             self.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
        }
        else
        {
            self.tintColor = tintColor
        }
    }
}
extension UIImage {
    convenience init(color: UIColor, size: CGSize) {
        UIGraphicsBeginImageContextWithOptions(size, false, 1)
        color.set()
        let ctx = UIGraphicsGetCurrentContext()!
        ctx.fill(CGRect(origin: .zero, size: size))
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        self.init(data: image.pngData()!)!
    }
}

XCODE 11.1 & iOS 13

基于@Jigar Darji 的回答,但实现更安全。

我们首先创建一个可失败的便利初始化器:

extension UIImage {

convenience init?(color: UIColor, size: CGSize) {
    UIGraphicsBeginImageContextWithOptions(size, false, 1)
    color.set()
    guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
    ctx.fill(CGRect(origin: .zero, size: size))
    guard
        let image = UIGraphicsGetImageFromCurrentImageContext(),
        let imagePNGData = image.pngData()
        else { return nil }
    UIGraphicsEndImageContext()

    self.init(data: imagePNGData)
   }
}

然后我们扩展 UISegmentedControl:

extension UISegmentedControl {

func fallBackToPreIOS13Layout(using tintColor: UIColor) {
    if #available(iOS 13, *) {
        let backGroundImage = UIImage(color: .clear, size: CGSize(width: 1, height: 32))
        let dividerImage = UIImage(color: tintColor, size: CGSize(width: 1, height: 32))

        setBackgroundImage(backGroundImage, for: .normal, barMetrics: .default)
        setBackgroundImage(dividerImage, for: .selected, barMetrics: .default)

        setDividerImage(dividerImage,
                        forLeftSegmentState: .normal,
                        rightSegmentState: .normal, barMetrics: .default)

        layer.borderWidth = 1
        layer.borderColor = tintColor.cgColor

        setTitleTextAttributes([.foregroundColor: tintColor], for: .normal)
        setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
    } else {
        self.tintColor = tintColor
    }
  }
}

IOS 13 和 Swift 5.0 (Xcode 11.0)段控制 100% 工作

 if #available(iOS 13.0, *) {
      yoursegmentedControl.backgroundColor = UIColor.black
      yoursegmentedControl.layer.borderColor = UIColor.white.cgColor
      yoursegmentedControl.selectedSegmentTintColor = UIColor.white
      yoursegmentedControl.layer.borderWidth = 1

      let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]    
      yoursegmentedControl.setTitleTextAttributes(titleTextAttributes, for:.normal)

      let titleTextAttributes1 = [NSAttributedString.Key.foregroundColor: UIColor.black]
      yoursegmentedControl.setTitleTextAttributes(titleTextAttributes1, for:.selected)
  } else {
              // Fallback on earlier versions
}

虽然上面的答案很好,但大多数答案都将所选句段内的文本颜色弄错了。我创建了 UISegmentedControl 子类,您可以在 iOS 13 和 pre-iOS 13 设备上使用它,并像在 pre-iOS 上一样使用 tintColor 属性 13 台设备。

    class LegacySegmentedControl: UISegmentedControl {
        private func stylize() {
            if #available(iOS 13.0, *) {
                selectedSegmentTintColor = tintColor
                let tintColorImage = UIImage(color: tintColor)
                setBackgroundImage(UIImage(color: backgroundColor ?? .clear), for: .normal, barMetrics: .default)
                setBackgroundImage(tintColorImage, for: .selected, barMetrics: .default)
                setBackgroundImage(UIImage(color: tintColor.withAlphaComponent(0.2)), for: .highlighted, barMetrics: .default)
                setBackgroundImage(tintColorImage, for: [.highlighted, .selected], barMetrics: .default)
                setTitleTextAttributes([.foregroundColor: tintColor!, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .normal)

                setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
                layer.borderWidth = 1
                layer.borderColor = tintColor.cgColor

// Detect underlying backgroundColor so the text color will be properly matched

                if let background = backgroundColor {
                    self.setTitleTextAttributes([.foregroundColor: background, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .selected)
                } else {
                    func detectBackgroundColor(of view: UIView?) -> UIColor? {
                        guard let view = view else {
                            return nil
                        }
                        if let color = view.backgroundColor, color != .clear {
                            return color
                        }
                        return detectBackgroundColor(of: view.superview)
                    }
                    let textColor = detectBackgroundColor(of: self) ?? .black

                    self.setTitleTextAttributes([.foregroundColor: textColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .selected)
                }
            }
        }

        override func tintColorDidChange() {
            super.tintColorDidChange()
            stylize()
        }
    }

    fileprivate extension UIImage {
        public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
          let rect = CGRect(origin: .zero, size: size)
          UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
          color.setFill()
          UIRectFill(rect)
          let image = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()

          guard let cgImage = image?.cgImage else { return nil }
          self.init(cgImage: cgImage)
        }
    }

使用 tintColorDidChange 方法,我们确保每次 tintColor 属性 段视图或任何基础视图发生变化时都会调用 stylize 方法,这是 iOS.

上的首选行为

结果:

如果你想将背景设置为清除你必须这样做:

if #available(iOS 13.0, *) {
  let image = UIImage()
  let size = CGSize(width: 1, height: segmentedControl.intrinsicContentSize.height)
  UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
  image.draw(in: CGRect(origin: .zero, size: size))
  let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  segmentedControl.setBackgroundImage(scaledImage, for: .normal, barMetrics: .default)
  segmentedControl.setDividerImage(scaledImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
}

结果如下:

SwiftUI Picker 缺少一些基本选项。对于试图在 iOS 13 或 14 的 SwiftUI 中使用 SegmentedPickerStyle() 自定义 Picker 的人,最简单的选择是使用 UISegmentedControl.appearance() 全局设置外观。这是一个示例函数,可以调用它来设置外观。

func setUISegmentControlAppearance() {
    UISegmentedControl.appearance().selectedSegmentTintColor = .white
    UISegmentedControl.appearance().backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.1)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.black], for: .normal)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
}

但是,如果您想要多个具有不同设置的控件,则使用 UISegmentedControl.appearance() 全局设置外观选项并不是很好。另一种选择是为 UISegmentedControl 实施 UIViewRepresentable。这是一个示例,它设置了原始问题中询问的属性并将 .apportionsSegmentWidthsByContent = true 设置为奖励。希望这会为您节省一些时间...

struct MyPicker: UIViewRepresentable {

    @Binding var selection: Int // The type of selection may vary depending on your use case
    var items: [Any]?

    class Coordinator: NSObject {
        let parent: MyPicker
        init(parent: MyPicker) {
            self.parent = parent
        }

        @objc func valueChanged(_ sender: UISegmentedControl) {
            self.parent.selection = Int(sender.selectedSegmentIndex)
        }
    }

    func makeCoordinator() -> MyPicker.Coordinator {
        Coordinator(parent: self)
    }

    func makeUIView(context: Context) -> UISegmentedControl {
        let picker = UISegmentedControl(items: self.items)

        // Any number of other UISegmentedControl settings can go here
        picker.selectedSegmentTintColor = .white
        picker.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.1)
        picker.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .normal)
        picker.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
        picker.apportionsSegmentWidthsByContent = true

        // Make sure the coordinator updates the picker when the value changes
        picker.addTarget(context.coordinator, action: #selector(Coordinator.valueChanged(_:)), for: .valueChanged)

        return picker
    }

    func updateUIView(_ uiView: UISegmentedControl, context: Context) {
        uiView.selectedSegmentIndex = self.selection
    }
 }

iOS 12+

我为背景颜色苦苦挣扎。将 .clear 颜色设置为背景颜色总是会添加默认的灰色。这是我修复的方法

self.yourSegmentControl.backgroundColor = .clear //Any Color of your choice

self.yourSegmentControl.setBackgroundImage(UIImage(), for: .normal, barMetrics: .default) //This does the magic

分隔线颜色

self.yourSegmentControl.setDividerImage(UIImage(), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default) // This will remove the divider image.

在iOS13及以上,当我在viewDidLoad中访问分段控件的subviews时,它有1个UIImageView。一旦我插入更多的段,它分别增加,所以 3 段意味着 3 UIImageView 作为分段控件的 subviews.

有趣的是,当它到达 viewDidAppear 时,分段控件的 subviews 变成了 3 UISegment(每个包含一个 UISegmentLabel 作为其子视图;这是您的文本) 和 4 UIImageView 如下所示:

viewDidLoad中的那3个UIImageView不知何故变成了UISegment,我们不想碰他们(但你可以尝试设置他们的形象或isHidden只是为了看看它如何影响 UI)。让我们忽略这些 private 类.

这 4 个 UIImageView 实际上是 3 个“正常”UIImageView(连同 1 个 UIImageView 子视图作为垂直分隔符)和 1 个“选定”UIImageView(即这实际上是您的 selectedSegmentTintColor 图片,请注意上面的屏幕截图中它下面没有子视图)。

在我的例子中,我需要一个白色背景,所以我不得不隐藏灰色背景图像(参见:https://medium.com/flawless-app-stories/ios-13-uisegmentedcontrol-3-important-changes-d3a94fdd6763)。我还想 remove/hide 段之间的垂直分隔符。

因此 viewDidAppear 中的简单解决方案无需设置分隔图像或背景图像(在我的例子中),就是简单地隐藏前 3 个 UIImageView:

// This method might be a bit 'risky' since we are not guaranteed of the internal sequence ordering, but so far it seems ok.
if #available(iOS 13.0, *) {
    for i in 0...(segmentedControl.numberOfSegments - 1) {
        segmentedControl.subviews[i].isHidden = true
    }
}

// This does not depend on the ordering sequence like the above, but this is also risky in the sense that if the UISegment becomes UIImageView one day, this will break.
if #available(iOS 13.0, *) {
    for subview in segmentedControl.subviews {
        if String(describing: subview).contains("UIImageView"),
           subview.subviews.count > 0 {
               subview.isHidden = true
        }
    }
}

选择你的毒药...