user6631218
user6631218

Reputation:

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!

Upvotes: 8

Views: 14914

Answers (6)

ajit.prazanna
ajit.prazanna

Reputation: 134

Use the code below for above ios 13,

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

Upvotes: 10

Kirby Todd
Kirby Todd

Reputation: 11566

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

Upvotes: 1

Kostas Tsoleridis
Kostas Tsoleridis

Reputation: 924

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)

Upvotes: 5

Mr. Xcoder
Mr. Xcoder

Reputation: 4795

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

Upvotes: 0

Sneha
Sneha

Reputation: 2216

To programmatically change tint color of segment,

segment.tintColor = UIColor.yellow

Upvotes: 9

KSR
KSR

Reputation: 1709

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

enter image description here

If you create the segmentedControl programmatically, then use this:

 segment.tintColor = UIColor.red

Upvotes: 2

Related Questions