1, select the control's creation and listen for the control selection value
Import UIKit
Class ViewController: UIViewController {
Override func viewDidLoad() {
super.viewDidLoad()
//Options can be pictures in addition to text
Let items = ["option one", "option two", UIImage(named: "g1")!] as [Any]
Let segmented = UISegmentedControl(items:items)
Segmented.center = self.view.center
segmented.selectedSegmentIndex = 1 //The second item is selected by default
segmented.addTarget(self, action: #selector(ViewController.segmentDidchange(_:)),
For: .valueChanged) //Add value change listener
self.view.addSubview(segmented)
}
Func segmentDidchange(_ segmented:UISegmentedControl){
/ / Get the index of the option
Print(segmented.selectedSegmentIndex)
/ / Get the selected text
Print(segmented.titleForSegment(at: segmented.selectedSegmentIndex))
}
}
2, select the selection of the control add and remove
/ / Add text options
segmented.insertSegment(withTitle: "new option", at:1, animated:true);
/ / Add image options
segmented.insertSegment(with: UIImage(named:"icon")!, at:1, animated: true)
// remove option
segmented.removeSegment(at: 1, animated:true)
3, modify the option color (including picture options)
segmented.tintcolor= uicolor. Redcolor ()
4, modify option Text
segmented.settitle ("Swfit", forsegmentatindex:1)
5, modify the option picture
(1) The following code image will automatically turn blue
segmented.setImage(UIImage(named:"icon"), forSegmentAt:2)
(2) Use the code below to keep the original color
segmented.setImage(UIImage(named:"icon")?.withRenderingMode(.alwaysOriginal), forSegmentAt:2)
6, modify the option content offset location
segmented.setContentOffset(CGSize(width:10, height:7), forSegmentAt:1)