tabBarController选定的索引在viewController中不起作用[Swift]

时间:2019-12-26 13:29:21

标签: ios swift uiviewcontroller uitabbarcontroller

在我的iOS应用中,我有一个带有3个项的tabBarController。当用户点击第二个项目时,将显示一个视图(CreateCommentsViewController),然后当用户点击关闭按钮时,我想更改tabBarController的选定索引(从1到0),但是这种方式不起作用:

class CreateCommentViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

}

func getTabBarController() -> UITabBarController? {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    guard let tabBarController = appDelegate.window?.rootViewController as? UITabBarController else { return nil }
    return tabBarController
}

@IBAction func dismissNewCommentView(_ sender: UIBarButtonItem) {

    let tabBarController = getTabBarController()!

    self.dismiss(animated: true) {
        tabBarController.selectedIndex = 0
    }
}
}

还有应用程序委托代码:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.main.bounds)
    window!.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: VIEW_CONTROLLER_IDS.TAB_BAR_CONTROLLER) as! UITabBarController
    window!.makeKeyAndVisible()

    return true
}

1 个答案:

答案 0 :(得分:0)

尝试更新您的操作(如果您使用Swift 5&5.1&5.2):

@IBAction func dismissNewCommentView(_ sender: UIBarButtonItem) {
    self.dismiss(animated: true) {
        if let tabBarController = UIApplication.shared.windows.first?.rootViewController as? UITabBarController {
            tabBarController.selectedIndex = 0
        }
    }
}