Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 添加/删除子视图时仅调用一次API_Ios_Swift_Uiviewcontroller_Uisegmentedcontrol - Fatal编程技术网

Ios 添加/删除子视图时仅调用一次API

Ios 添加/删除子视图时仅调用一次API,ios,swift,uiviewcontroller,uisegmentedcontrol,Ios,Swift,Uiviewcontroller,Uisegmentedcontrol,我有一个分段控件,单击分段通过向容器视图添加视图来显示视图。单击其他段控件时,将删除旧视图,并使用下面给出的函数添加新视图。以这种方式添加VC将调用我从API获取数据的viewDidLoad。在添加VC时,每次单击段时都会调用API。如何防止每次添加视图时调用API 是否有任何方法可以隐藏旧视图而不是删除它,这将阻止每次单击某个段时实例化VC 或者,是否有其他更好的方式在点击细分市场时显示VCs @IBAction func show(_ sender: UISegmentedControl)

我有一个分段控件,单击分段通过向容器视图添加视图来显示视图。单击其他段控件时,将删除旧视图,并使用下面给出的函数添加新视图。以这种方式添加VC将调用我从API获取数据的
viewDidLoad
。在添加VC时,每次单击段时都会调用API。如何防止每次添加视图时调用API

是否有任何方法可以隐藏旧视图而不是删除它,这将阻止每次单击某个段时实例化VC

或者,是否有其他更好的方式在点击细分市场时显示VCs

@IBAction func show(_ sender: UISegmentedControl) {
   
    switch sender.selectedSegmentIndex {
    case 0:
        let vc1 = VC1.instantiate()
        
        self.cycleFromViewController(oldViewController: self.currentVC!, toViewController: vc1)
        self.currentVC = vc1
           
    case 1:
        let vc2 = VC2.instantiate()
        self.cycleFromViewController(oldViewController: self.currentVC!, toViewController: vc2)
        self.currentVC = vc2
        
    default:
        break
            
    }
}


func cycleFromViewController(oldViewController: UIViewController, toViewController newViewController: UIViewController) {
    oldViewController.willMove(toParent: nil)
    self.addChild(newViewController)
    self.addSubview(subView: newViewController.view, toView:self.containerView!)
    newViewController.view.alpha = 0
    newViewController.view.layoutIfNeeded()
    UIView.animate(withDuration: 0.5, animations: {
        newViewController.view.alpha = 1
        oldViewController.view.alpha = 0
    },
                   completion: { finished in
                    oldViewController.view.removeFromSuperview()
                    oldViewController.removeFromParent()
                    newViewController.didMove(toParent: self)
    })
}
创造

然后在
viewdiload
内部创建并分配
vc1
vc2
并设置
currentVC=vc1


在播放完他们的
视图后。isHidden

,因此我首先将两个VCs添加为子视图,然后在show()中根据需要显示/隐藏它们?是的…………有效。简单有效,我早该想到的。
var vc1,vc2,currentVC:UIViewController?