[Swift] Let's use Segmented Control

I investigated how to use UISegmentedControl, so I wrote an article.

Implementation environment version
Swift 5
Xcode 12.0

What is Segmented Control?

A literal translation of Segmented Control Control device (control) divided into parts </ b>

Take a look at the official Apple documentation! スクリーンショット 2020-10-30 13.13.23.png

Very concisely Multiple individual buttons that can be operated horizontally </ b>.

Easy to use

image.pngスクリーンショット2020-10-3013.43.03.png

Select Attributes Inspector of Segmented Control,

Set the color when the button is selected with Selected Tint </ code> Set the number of buttons with Segments </ code> Set the button title with Title </ code>

Get the title of the selected button

python


 @IBAction func segmentedControl(_ sender: UISegmentedControl) {
        print(sender.titleForSegment(at: sender.selectedSegmentIndex)!)
    }

When you want to change the button selected during viewload

python


class ViewController: UIViewController {
    
    @IBOutlet weak var segmentedControl: UISegmentedControl!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        segmentedControl.selectedSegmentIndex = 1
    }

SegmentIndex increases from the left with 0, 1, 2, ... This time, segmentedControl.selectedSegmentIndex = 1 So, since 1 </ code> is assigned, it is displayed like this after startup. image.png


It seems that Segmented control can be set not only with characters but also with images, so if you are interested, please try it.

Reference: Apple Official Document (UISegmentedControl)

Recommended Posts