【问题标题】:How do I filter view controller by type?如何按类型过滤视图控制器?
【发布时间】:2022-02-11 00:15:14
【问题描述】:

这是我的简单功能:

func popTo<T: UIViewController>(type: T.Type, from context: UINavigationController?) {
    let mytype = type
    guard let controller = context?.viewControllers.first(where: { $0 is T }) else {
        return
    }
    print(mytype) //1
    print(context?.viewControllers) //2
    print(controller) //3
    context?.popToViewController(controller, animated: true)
}

设置断点并打印以下行后,我得到控制台输出:

PLZ.GroupViewController //1

▿ Optional<Array<UIViewController>> //2
  ▿ some : 5 elements
    ▿ 0 : <PLZ.GroupsViewController: 0x11dd68660>
    ▿ 1 : <PLZ.GroupViewController: 0x11f415c70>
    ▿ 2 : <PLZ.ProductViewController: 0x11f619d00>
    ▿ 3 : <PLZ.ConfirmViewController: 0x11f538cd0>
    ▿ 4 : <PLZ.ConfirmationViewController: 0x11f53e330>

<PLZ.GroupsViewController: 0x11dd68660> //3

为什么它应该返回GroupsViewController 而应该返回GroupViewController

如何调用该函数?

if let type = viewModel.returnControllerType {
    print(type) //4
    self?.router.popTo(type: type, from: self?.navigationController)
} 

PLZ.GroupViewController //4

returnControllerType 已定义:

let returnControllerType: UIViewController.Type?

【问题讨论】:

  • GroupViewController & GroupsViewController 之间是否存在继承关系?
  • 不,两者都直接继承自UIViewController
  • 我想它搜索 UIViewController,而不是 GroupViewController。有没有办法检查它的类型参数?
  • 你怎么称呼这个popTo函数?
  • @Sweeper 我更新了问题。

标签: ios swift


【解决方案1】:

有史以来最简单的解决方案是:

func popTo<T: UIViewController>(type: T.Type, from context: UINavigationController?) {
    guard let controller = context?.viewControllers.first(where: { $0.isKind(of: type) }) else {
        return
    }
    context?.popToViewController(controller, animated: true)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2015-08-03
    • 2010-12-11
    相关资源
    最近更新 更多