let items = ["Purple", "Green", "Blue"]
let customSC = UISegmentedControl(items: items)
customSC.selectedSegmentIndex = 0
// Set up Frame and SegmentedControl
let frame = UIScreen.main.bounds
customSC.frame = CGRect(x: frame.minX + 10, y: frame.height - 100, width: frame.width - 20, height: 48)
// Style the Segmented Control
customSC.layer.cornerRadius = 5.0 // Don't let background bleed
customSC.backgroundColor = UIColor.gray
customSC.tintColor = UIColor.white
let myAttribute1 = [ NSAttributedStringKey.font: UIFont(name: "Menlo-Regular", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.init(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)]
let myAttribute2 = [ NSAttributedStringKey.font: UIFont(name: "Menlo-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.init(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)]
customSC.setTitleTextAttributes(myAttribute1, for: .normal)
customSC.setTitleTextAttributes(myAttribute2, for: .selected)
customSC.layer.cornerRadius = 5.0
customSC.clipsToBounds = true
customSC.setDividerImage(UIImage(), forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)
customSC.setBackgroundImage(#imageLiteral(resourceName: "img_header"), for: .selected, barMetrics: .default)
customSC.setBackgroundImage(UIImage(), for: .normal, barMetrics: .default)
// Add target action method
customSC.addTarget(self, action: #selector(changeColor(_:)), for: .valueChanged)
// Add this custom Segmented Control to our view
self.view.addSubview(customSC)
Метод делегатов для клика сегмента
@objc func changeColor(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 1:
break;
case 2:
break;
default:
break;
}
}
Вывод: