Search code examples
iosswiftuisegmentedcontrol

switch between views ios using UISegmentedControl without using alpha?


I have UISegmentedControl and I use it to switch between 2 UI views but I have problem with my views make the app to chatty with web APIs.each view will call its API to bring data for each view. I want to make the app parent view the load each view without user alpha of child

import UIKit

class UsersGroupsViewController: UIViewController {

        @IBOutlet weak var usersView:UIView!
        @IBOutlet weak var groupView:UIView!

        @IBOutlet weak var segmentedControlViews: UISegmentedControl!

        override func viewDidLoad() {
            super.viewDidLoad()

            // Do any additional setup after loading the view.

            let font = UIFont.systemFont(ofSize: 15)
            segmentedControlViews.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
        }

        @IBAction func switchViews(_ sender: UISegmentedControl) {
            if sender.selectedSegmentIndex == 0 {
                usersView.alpha = 1
                groupView.alpha = 0
            } else {
                usersView.alpha = 0
                groupView.alpha = 1
            }
        }
}

Solution

  • instead of using alpha use isHidden

    @IBOutlet weak var segmentedControlViews: UISegmentedControl!
    @IBOutlet weak var usersView: UIView!
    @IBOutlet weak var groupView: UIView!
    
    @IBAction func indexChanged(_ sender: UISegmentedControl) {
        switch sender.selectedSegmentIndex {
        case 0:
            usersView.isHidden = true
            groupView.isHidden = false
        case 1:
            usersView.isHidden = false
            groupView.isHidden = true
        default:
            break
    }