更改 UISegmentedControl 中特定段的标题文本颜色?

问题描述 投票:0回答:6

如何更改 UISegmentedControl 的一个特定片段的文本颜色?我想让它们保持正常,除了特定的部分应该是不同的颜色,无论它是否被选择。

ios iphone uikit uisegmentedcontrol
6个回答
4
投票
@IBDesignable
    class DesignableSegmentControl: UISegmentedControl{
    }
    extension UISegmentedControl{
        @IBInspectable
        var textColor: UIColor{
            get {
                return self.textColor
            }
            set {
                let unselectedAttributes = [NSAttributedString.Key.foregroundColor: newValue,
                                            NSAttributedString.Key.font:  UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)]
                self.setTitleTextAttributes(unselectedAttributes, for: .normal)
                self.setTitleTextAttributes(unselectedAttributes, for: .selected)
            }
        }
    }

只需更改分段控件的类名,如下所示:

[更改班级名称]:

[更改文字颜色]:


2
投票

对于 Swift 5

segmentControl.setTitleTextAttributes( [NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected) 

1
投票

没有任何内置方式;正如您可能已经发现的那样,

setTitleTextAttributes
适用于所有细分。您必须将文本绘制为图像并使用它。


1
投票

更新了 Swift 4.1

UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)

斯威夫特3.1

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)

对于早期 Swift 版本:

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .selected)

0
投票

您可以实现自己的分段控件进行定制。

  1. 添加两个具有相同 UI 的按钮作为分段控件。
  2. 绕过角落。
  3. 单击时根据您的需要设置背景颜色并清除其他背景并取消选择。

这样定制的空间就很大。 GitHub 上还提供了许多自定义分段控件。 你可以试试这个

https://github.com/gmarm/BetterSegmentedControl


-1
投票

只需添加这行代码:

UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)

© www.soinside.com 2019 - 2024. All rights reserved.