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

时间:2017-01-09 09:22:07

标签: ios iphone swift uisegmentedcontrol

我想在Swift 3中更改UISegmentedControl选定段的 tintColor 。 我在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
  // 

}

}

谢谢!

6 个答案:

答案 0 :(得分:3)

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

segment.tintColor = UIColor.yellow

答案 1 :(得分:3)

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

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

答案 2 :(得分:1)

在Main.storyboard中,选择segmentControl并更改属性“Tint”,如下面的屏幕截图所示:

enter image description here

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

 segment.tintColor = UIColor.red

答案 3 :(得分:0)

将以下代码添加到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
    }
}
}

这是此问题的接受答案的快速版本:UISegmentedControl selected segment color

答案 4 :(得分:0)

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

您可以在iOS 13 UISegmentedControl: 3 important changes

上找到更完整的更改说明。

答案 5 :(得分:0)

将以下代码用于上述ios 13

HashSet<string>
相关问题