ios - 删除当前 View 并使用分段 Controller 添加另一个 View

标签 ios swift

我正在尝试使用分段 Controller 来交换我的 viewsControllers。但问题是,我不知道这样做的最佳逻辑。目前我正在执行以下操作,这实际上导致了内存泄漏并且没有正确删除 View 。

如果单击分段索引(inViewDidLoad,所选索引为 1),我会更新我的 View 是的,我知道这根本不合逻辑,但这就是我需要你帮助的原因:

private func updateView() {
        if segmentedControl.selectedSegmentIndex == 0 {
            add(asChildViewController: difficulty2ViewController)
        }else if segmentedControl.selectedSegmentIndex == 1{
            add(asChildViewController: difficulty3ViewController)
        }else if segmentedControl.selectedSegmentIndex == 2{
            add(asChildViewController: difficulty4ViewController)
        }else if segmentedControl.selectedSegmentIndex == 3{
            add(asChildViewController: difficulty5ViewController)
        }else if segmentedControl.selectedSegmentIndex == 4{
            add(asChildViewController: difficulty6ViewController)
        }else if segmentedControl.selectedSegmentIndex == 5{
            add(asChildViewController: difficulty7ViewController)
        }
    }

像这样我添加 View :

private func add(asChildViewController viewController: UIViewController) {
        // Add Child View Controller
        addChildViewController(viewController)

        // Add Child View as Subview
        view.addSubview(viewController.view)

        //Little animation
        viewController.view.alpha = 0.0
        UIView.animate(withDuration: 0.3) {
            viewController.view.alpha = 1.0
        }

        // Configure Child View
        viewController.view.frame = view.bounds
        viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        // Notify Child View Controller
        viewController.didMove(toParentViewController: self)
    }

然后我就这样删除了 View :

private func remove(asChildViewController viewController: UIViewController) {
        // Notify Child View Controller
        viewController.willMove(toParentViewController: nil)

        // Remove Child View From Superview
        viewController.view.removeFromSuperview()

        // Notify Child View Controller
        viewController.removeFromParentViewController()
    }

我的问题是,如何删除当前 View 然后添加新 View ?或者有更好的解决方案吗?

最佳答案

segmentedControl.selectedSegmentIndex 上使用switch cases
您可以评估每个段的 typedefing enum 声明,将提高理智和代码易读性

关于ios - 删除当前 View 并使用分段 Controller 添加另一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42587647/

相关文章:

ios - 如何在 Swift 5 中检查字符串是否以字母开头?

swift - 使用 Swift 从 firebase 数据库读取

ios - Swift 自定义 NavBar 后退按钮图像和文本

ios - 在 Mac Catalyst 中访问 NSWindow

swift - 收到错误 : Use of unresolved identifier 'NSRectFill' , 但 __NSRectFill 有效,为什么?

ios - 延迟沿着 BezierPath 动画 UIView

swift - xmpp_messenger_ios Swift MUC swift

ios - 带有图像的 UITableview 滚动速度非常慢

ios - XLIFF 中的 xib 缺少字符串(Xcode 基本本地化)

ios - MVVM 中的分析