Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 553
aircraft Avatar asked Dec 20 '25 15:12

aircraft


2 Answers

More simple approach:

segmentControl.layer.borderWidth = 1.0
segmentControl.layer.cornerRadius = 5.0
segmentControl.layer.borderColor = UIColor.red.cgColor
segmentControl.layer.masksToBounds = true
like image 139
Tiago Mendes Avatar answered Dec 23 '25 08:12

Tiago Mendes


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)

like image 32
Pochi Avatar answered Dec 23 '25 06:12

Pochi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!