aircraft
aircraft

Reputation: 26886

How to set borderColor of `UISegmentControl` in `swift`?

Before asking the question, I have searched stackoverflow, find a related post:

change segmentControl border color

But we can see it is in objective-c language.

So how can we change the borderColor of UISegmentControl in swift ?

Upvotes: 3

Views: 5473

Answers (5)

Chathuranga
Chathuranga

Reputation: 316

Add the outlet

@IBOutlet weak var customSegment: UISegmentedControl!

then in your viewDidload method

    customSegment.layer.borderWidth = 1.0
    customSegment.layer.cornerRadius = 5.0
    customSegment.layer.borderColor = UIColor.red.cgColor
    customSegment.layer.masksToBounds = true

enter image description here

Upvotes: 1

Haya Hashmat
Haya Hashmat

Reputation: 137

self.segementControl.layer.borderWidth = 0.3
self.segementControl.layer.cornerRadius = 3.0
self.segementControl.layer.borderColor = UIColor.orange.cgColor

Upvotes: -1

Tiago Mendes
Tiago Mendes

Reputation: 5156

More simple approach:

segmentControl.layer.borderWidth = 1.0
segmentControl.layer.cornerRadius = 5.0
segmentControl.layer.borderColor = UIColor.red.cgColor
segmentControl.layer.masksToBounds = true

Upvotes: 3

aircraft
aircraft

Reputation: 26886

We can set the background image to achieve the effect.

    let customSegmentedControl = UISegmentedControl.appearance()
    //customSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.red], for: UIControlState.normal)

    customSegmentedControl.setBackgroundImage(UIImage.init(named: "ni2.png"), for: .normal, barMetrics: .default)
    customSegmentedControl.setBackgroundImage(UIImage.init(named: "ni.png"), for: .selected, barMetrics: .default)

Upvotes: 0

Pochi
Pochi

Reputation: 13459

You literally just have to convert the code to swift...

let customSegmentedControl = UISegmentedControl.appearance()    
customSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.red], for: UIControlState.normal)

But I believe the code you posted changes the actual color of the letters, not the color outside. The color outside is called "tint" and it's changed like this:

customSegmentedControl.tintColor = UIColor.blue

EDIT: For ONLY changing the border

Since each segment in the SegmentedControl is an actual UIView you can access them directly and customize them per your needs as in this answer.

Or you can set the "background image" which I believe can be set to the color you need. (Although the method above seems less complicated)

Upvotes: 1

Related Questions