调用将 UIViewController 推入闭包内部的函数,就好像它在外面一样

Call function pushing UIViewController inside closure as though it were outside

我在另外两个闭包(entireDescView.customize(第二个闭包)和description(第一个闭包))中有一个闭包(handleMentionTap)。现在我想调用位于同一个 class 中的函数 pushProfileController(of: String)(为了推送另一个视图控制器(newController)。需要在闭包内部调用这些函数,因为在外面调用它们会导致内存泄漏,原因我目前不知道(我正在使用一个名为 ActiveLabel 的库,不是我自己写的)。但是,newController 没有被推送(即使我使用 DispatchQueue.main.async 如 Whosebug 上有关类似问题的一些答案中所建议的那样。不过 newController 似乎已创建及其数据集(我正在使用 var passedData: String? { didSet { print(passedData) } } 打印数据)。如何推送控制器就好像它在闭包之外(例如 self.pushProfileController(of: username)?非常感谢你的帮助!

swift(所有内容都在同一个 class):

var pushingViewController = false

//...

func pushProfileController(of: String) {
    if self.pushingViewController == false {
        self.pushingViewController = true
        DispatchQueue.main.async {
            let newController = NewController()
            newController.passedData = of //passedData is a string
            self.navigationController?.pushViewController(newController, animated: true)
        }

        self.pushingViewController = false
    }
}

let description: ActiveLabel = {

    let entireDescView = ActiveLabel()

    //set properties of controls container view

    //recognize (@hotel_x) and be able to push controller of 'hotel_x'
    entireDescView.customize({ (entireDescView) in
        entireDescView.enabledTypes = [.mention]
        entireDescView.mentionColor = UIColor(red: 25/255, green: 153/255, blue: 1, alpha: 1)
        entireDescView.handleMentionTap { username in
            self.pushProfileController(of: username) //also tried ThisClass().pushProfileController(of: username) which didn't push the controller either
        }
    })

    return entireDescView

}()

您是否检查过 navigationController? 是否存在?

在尝试推送 viewController 之前尝试添加以下内容:

func pushProfileController(of: String) {
    if self.pushingViewController == false {
        self.pushingViewController = true
        DispatchQueue.main.async {
            guard let navController = self.navigationController else { return print("navigationController was nil") }
            let newController = NewController()
            newController.passedData = of //passedData is a string
            navController.pushViewController(newController, animated: true)
        }

        self.pushingViewController = false
    }
}