CompC
CompC

Reputation: 415

Change title text color of a specific segment in UISegmentedControl?

How can I change the text color of just one specific segment of a UISegmentedControl? I want to keep them all normal, except for a specific segment which should be a different color, whether it is selected or not.

Upvotes: 4

Views: 7485

Answers (5)

mohsen
mohsen

Reputation: 5078

for swift 5:

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

Upvotes: 2

Mahendra_lariya
Mahendra_lariya

Reputation: 39

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

Just change you segment control's class name as shown below:

[change class name]:
enter image description here

[change text color]:
enter image description here

Upvotes: 3

Sham Dhiman
Sham Dhiman

Reputation: 1566

Updated 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)

For Earlier Swift Version:

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

Upvotes: 1

Himan Dhawan
Himan Dhawan

Reputation: 924

You can implement your own segmented control for customisation.

  1. Add two buttons with same UI as segmented control.
  2. Round the corners.
  3. On click make the background colour according to your need and clear back ground of other and make it unselected.

In this way there is large scope for customisation. Also there are many custom segmented control are available at GitHub. You can try this

https://github.com/gmarm/BetterSegmentedControl

Upvotes: 0

matt
matt

Reputation: 535989

There isn't any built-in way; as you've probably figured out, setTitleTextAttributes applies to all the segments. You would have to draw your text as an image and use that instead.

Upvotes: 1

Related Questions