【问题标题】:Call API only once when adding/removing subview添加/删除子视图时仅调用一次 API
【发布时间】:2021-05-29 22:28:52
【问题描述】:

我有一个分段控件,单击分段通过将视图添加到容器视图来显示视图。单击其他段控件时,将删除旧视图并使用下面给出的函数添加新视图。以这种方式添加 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)
    })
}

【问题讨论】:

    标签: ios swift uiviewcontroller uisegmentedcontrol


    【解决方案1】:

    创建

    var vc1,vc2,currentVC:UIViewController? 
    

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

    在那之后和他们的view.isHidden一起玩

    【讨论】:

    • 所以我先将两个 VC 添加为子视图,然后在 show() 中根据需要显示/隐藏它们?
    • 有效。德克萨斯州。简单有效,早该想到的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多