简体   繁体   中英

How to change selected segment tintColor of UISegmentedControl in Swift

I want to change the tintColor of UISegmentedControl selected segment in Swift 3. I've searched a lot of answers in Objective-c...
This is my code:

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
  // 

}

}

Thanks!

Use the code below for above ios 13,

if #available(iOS 13.0, *) {
        segment.selectedSegmentTintColor = .red
} else {
        segment.tintColor = .red
}

To programmatically change tint color of segment,

segment.tintColor = UIColor.yellow

if you want to set the color of the title for example, you can do it like this:

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

In Main.storyboard, select segmentControl and change the property "Tint" as shown in below screenshot:

在此处输入图片说明

If you create the segmentedControl programmatically, then use this:

 segment.tintColor = UIColor.red

A new property was added in iOS 13: selectedSegementTintColor . The old tintColor property no longer works in iOS 13.

You can find a more complete writeup of the changes here iOS 13 UISegmentedControl: 3 important changes

Add the following code to your changeValue function:

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
    }
}
}

This is a swift version of the accepted answer from this question: UISegmentedControl selected segment color

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM