Home > Mobile >  UISegmentedControl and View switching problem
UISegmentedControl and View switching problem

Time:10-05


So I've made a code in which I have 3 options in UISegmentedControl which should show you one of 3 Views ( green with 2 text fields, sub-view blue with 2 buttons and sub-view purple with 2 IUImageView)


At first everything looked easy, but then I've realized that my VC only first View, and ignores 2 and 3. So when I click second and third segmented control all I see is a blanc screen.
Weirdly, but when I've changed 1 seg control to show me blue view, instead of green, it also showed me blanc screen.


I'm still a beginner so it's hard for me to understand where is a problem here(
Maybe someone can help me.
Thanks!
hierarchy in storyboard

 import UIKit

class ThirdViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        greenView.isHidden = false. // in this part I've tried to make the second view visible instead of first. It did not work. 
        
        blueView.isHidden = true
        purpleView.isHidden = true
    }

    @IBOutlet weak var greenView: UIView!
    
    @IBOutlet weak var blueView: UIView!
   
    @IBOutlet weak var purpleView: UIView!
    
    @IBAction func didChangeSC(_ sender: UISegmentedControl) {
   
        switch  sender.selectedSegmentIndex {
        case 0 :
            greenView.isHidden = false
            
            blueView.isHidden = true
            purpleView.isHidden = true
            
        case 1 :
            blueView.isHidden = false
            
            greenView.isHidden = true
            purpleView.isHidden = true
        case 2 :
            purpleView.isHidden = false
            
            greenView.isHidden = true
            blueView.isHidden = true
            
            
        default:
            break
         
        }
    }
        
    
    
    

    /*
     // I've also tried to change the visibility but it didn't work.Here is how I did it.


     case 0 :
         greenView.alpha = 1
         
         blueView.alpha = 0
         purpleView.alpha = 0
         
     case 1 :
         blueView.alpha = 1
         
         greenView.alpha = 0
         purpleView.alpha = 0
     case 2 :
         purpleView.alpha = 1
         
         greenView.alpha = 0
         blueView.alpha = 0
     */

CodePudding user response:

The issue is your BlueView and PurpleView are sub views of the GreenView. Since they are subViews, when you hide the GreenView, they also get hidden. So make all three views siblings (in the same level)

Now your view hierarchy is below

- View
  - GreenView
    - BlueView 
      - PurpleView 

Change it to

- View
  - GreenView
  - BlueView 
  - PurpleView 
  • Related