Skip to content

Instantly share code, notes, and snippets.

@anoop4real
Last active September 15, 2022 06:52
Show Gist options
  • Save anoop4real/deffa9bbed3741b6c3f19c07d8c87502 to your computer and use it in GitHub Desktop.
Save anoop4real/deffa9bbed3741b6c3f19c07d8c87502 to your computer and use it in GitHub Desktop.
CapsuleSegmentedControl
import UIKit
import PlaygroundSupport
// Ref: https://stackoverflow.com/questions/58315497/selectedtintcolor-of-segment-control-is-not-rounded-corner-on-ios-13
class CapsuleSegmentedControl: UISegmentedControl {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = self.bounds.size.height / 2.0
layer.borderColor = UIColor.gray.cgColor
layer.borderWidth = 1.0
layer.masksToBounds = true
clipsToBounds = true
if #available(iOS 13.0, *) {
selectedSegmentTintColor = .clear
} else {
tintColor = .clear
}
for (index, subview) in subviews.enumerated() {
if ((subviews[index] as? UIImageView) != nil) && index == selectedSegmentIndex {
subview.backgroundColor = .white
subview.layer.cornerRadius = subview.bounds.size.height / 2.0
} else {
subview.backgroundColor = .clear
}
}
}
}
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
self.view = view
setUpView()
}
private func setUpView() {
let segmentedControl = CapsuleSegmentedControl(items: ["One", "Two", "Three"])
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.backgroundColor = UIColor.gray
view.addSubview(segmentedControl)
segmentedControl.selectedSegmentIndex = 0
NSLayoutConstraint.activate([
segmentedControl.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 15),
segmentedControl.topAnchor.constraint(equalTo: view.topAnchor, constant: 44),
segmentedControl.heightAnchor.constraint(equalToConstant: 31)
])
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
![Image](https://user-images.githubusercontent.com/6782228/95784960-1ed86e80-0cd5-11eb-89e6-5d871a902ee1.png)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment