如何在 Swift 中更改 UISegmentedControl 的选定段 tintColor

How to change selected segment tintColor of UISegmentedControl in Swift

我想更改 tintColor Swift 中 UISegmentedControl 选定段的 3。 我在 Objective-c...
中搜索了很多答案 这是我的代码:

class ViewController:UIViewController{

var segment:UISegmentedControl

override func viewDidLoad() {
super.viewDidLoad()

segment.insertSegment(withTitle: "AAA", at: 0, animated: true)
segment.insertSegment(withTitle: "BBB", at: 1, animated: true)
segment.insertSegment(withTitle: "CCC", at: 2, animated: true)

segment.addTarget(self, action: #selector(changeValue), for: .valueChanged)
segment.selectedSegmentIndex = 0

view.addSubview(segment)

}
  func changeValue(sender:AnyObject) {

  //I don't know how to do that change color when segment selected
  // 

}

}

谢谢!

在 Main.storyboard、select segmentControl 中更改 属性 "Tint" 如下图所示:

如果您以编程方式创建 segmentedControl,则使用:

 segment.tintColor = UIColor.red

将以下代码添加到您的 changeValue 函数中:

func changeValue(sender: UISegmentedControl){
for i in 0..<sender.subviews.count {
    if sender.subviews[i].isSelected() {
        var tintcolor = UIColor.red // choose the color you want here
        sender.subviews[i].tintColor = tintcolor
    }
    else {
        sender.subviews[i].tintColor = nil
    }
}
}

这是这个问题的已接受答案的 swift 版本:UISegmentedControl selected segment color

要以编程方式更改段的色调,

segment.tintColor = UIColor.yellow

如果你想设置标题的颜色,你可以这样做:

let titleTextAttributes = [NSForegroundColorAttributeName: Color.blue]
segmentedControl.setTitleTextAttributes(titleTextAttributes, forState: .Selected)

在 iOS 13 中添加了一个新的 属性:selectedSegementTintColor。旧的 tintColor 属性 不再适用于 iOS 13.

您可以在此处找到更完整的更改说明 iOS 13 UISegmentedControl: 3 important changes

上面ios13,

使用下面的代码
if #available(iOS 13.0, *) {
        segment.selectedSegmentTintColor = .red
} else {
        segment.tintColor = .red
}