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

5

我该如何改变 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)
            }
        }
    }

只需要将您的段控件的类名更改如下所示:
[更改类名]:
enter image description here
[更改文本颜色]:
enter image description here

这并没有实现OP所要求的,即仅更改一个部分的字体属性“无论是否被选中”。 - undefined

2

针对Swift 5的内容:

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

你的yourSegment是什么? - undefined
@adamjansch 在UIkit中,它将是一个UISegmentedControl对象。 - undefined
这基本上是与之前给出的答案相同,无法解决提问者所需的问题。 - undefined

1

没有内置的方法;正如你可能已经发现的那样,setTitleTextAttributes适用于所有的片段。您需要将文本绘制为图像,然后使用它。


1

更新 Swift 4.1

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

Swift 3.1

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

对于早期的Swift版本:

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

这将为所有段设置标题文本属性。我只想更改一个单独段落的文本颜色。 - CompC
这也将为在此之后实例化的所有UISegmentedControls的所有段设置标题文本属性。 - undefined

0

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

  1. 添加两个与分段控件相同的按钮。
  2. 将角落变圆。
  3. 点击时,根据需要设置背景颜色,并清除其他背景并将其取消选择。

通过这种方式,有很大的自定义空间。 此外,GitHub上还有许多自定义分段控件可用。 您可以尝试一下。

https://github.com/gmarm/BetterSegmentedControl


1
虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。如果链接页面更改,仅有链接的答案可能会失效。- 来自审查 - Sociopath
请再检查一遍。 - Himan Dhawan

-1
只需添加以下代码行:
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)

你的回答可以通过提供更多支持信息来改善。请编辑以添加进一步详细信息,例如引用或文档,以便他人可以确认您的答案是否正确。您可以在帮助中心中找到有关撰写良好回答的更多信息。 - Community
这个回答和上面的@sham的回答是一样的,也没有回答到OP想要的。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接