Search code examples
swiftlabelhideuisegmentedcontrol

Hiding elements in swift using segmented controls


I'm trying to hide specific labels in my view with a segmented control. In case 0 I only want to display certain labels # 1/2/5, and in case two I want to display labels # 2/4/5.

But something is wrong.... Nothing happens when I select the second segment, and all my content gets hidden after then pressing the first segment.

Am I on the right path, or should I use something conditional? (label"A" is hidden if segment 0 or something)

    @IBAction func DriveTypeChange(_ sender: Any) {
            if DriveTypeControler.selectedSegmentIndex == 0 {
                InVenueDriveMaxLoad.isHidden = true
            }
            if DriveTypeControler.selectedSegmentIndex == 1 {
                InVenueDriveMaxLoad.isHidden = false
        }
    ```

    }

Solution

  • First of all create @IBAction for valueChanged action of UISegmentedControl.

    Now, as per your requirement to hide/show labels based on selectedSegmentIndex,

    @IBAction func driveTypeChanged(_ sender: UISegmentedControl) {
        label1.isHidden = (sender.selectedSegmentIndex == 1)
        label2.isHidden = false
        label4.isHidden = (sender.selectedSegmentIndex == 0)
        label5.isHidden = false
    }