按下特定选项卡时设置委托

Setting a delegate when a specific tab is pressed

我有一个委托,我称之为 logoSelectionDelegate。委托有一个函数来指示用户是否更改了他们的徽标。

func userDidChangeLogo(image1: UIImage) {
    pickedImage = image1
}

我曾经使用 prepareForSegue 函数设置代理,如下所示:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SettingsIdentifier" {
        let viewController:SelectALogoViewController = segue.destinationViewController as SelectALogoViewController
        viewController.delegate=self

        if pickedImage != nil {

            viewController.pickedImage = pickedImage
        }



    }
}

这工作正常,但是,现在我已更改为选项卡式应用程序,并且我想在按下 "settings" 选项卡时设置 logoSelectionDelegate。现在我不确定该怎么做,我将我的 TabBarController 设置为 logoSelectionDelegate,在 TabBarController.swift 文件中实现我的委托函数,然后使用 didSelectViewController 方法尝试设置 logoSelectionDelegate,如下所示:

 func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) -> Bool {

    if (tabBarController.selectedIndex == 1) {

        let viewController:SelectALogoViewController! = viewController as? SelectALogoViewController
        viewController.delegate=self

        if pickedImage != nil {

            viewController.pickedImage = pickedImage
        }

        println("Yes")
    }



    return true



}

我无法让它工作,欢迎您发表评论/回答

您可以通过以下方式访问标签栏视图控制器:

let viewController = self.tabBarController?.viewControllers?[1] as? SelectALogoViewController
    viewController?.delegate = self

或者另一种选择是直接调用您的方法并完全删除 delegate/protocol 语法:

let viewController = self.tabBarController?.viewControllers?[1] as? SelectALogoViewController
    viewController?.doSomething()