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

问题描述

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

有什么办法可以隐藏旧视图而不是删除它,这将防止每次单击一个段时实例化 VC。

或者,还有其他更好的方法可以在细分点击时显示 VC 吗?

@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)
    })
}

解决方法

创建

var vc1,vc2,currentVC:UIViewController? 

然后在 viewDidLoad 中创建并分配 vc1vc2 并设置 currentVC = vc1

在那之后玩他们的view.isHidden

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...