如何解决添加/删除子视图时只调用一次 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
中创建并分配 vc1
和 vc2
并设置 currentVC = vc1
在那之后玩他们的view.isHidden
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。