iOS:获得 'UIViewController' 个 'UIButton'

iOS: Get 'UIViewController' of 'UIButton'

我需要在 UIButton 的子 class 中获取 UIViewController 的引用(对象)。在这里我尝试了一些但失败了。

class NavigationBarButton: UIButton {


    override func didMoveToSuperview() {
        super.didMoveToSuperview()

        var viewController: UIViewController? {
            var nextResponder: UIResponder? = self
            repeat {
                nextResponder = nextResponder?.next

                if let viewController = nextResponder as? UIViewController {
                    return viewController
                }

            } while nextResponder != nil

            return nil
        }

        guard let vcViewController = self.viewController else { print("NavigationBarButton view controller could not found"); return }

        print("handle further operations with ViewController of Button")

    }

}

class FirstVC: UIViewController {

    @IBOutlet weak var myButton: NavigationBarButton?


}

Result:
NavigationBarButton view controller could not found

有没有其他方法,无需更新 UIViewController,我可以在 UIButton 的子 class 中获取视图控制器引用。任何其他 UIButton 方法都可以在这里帮助我,在那里我可以获得按钮的视图控制器。

类似的SO QUE。但对这个问题没有用:Get current UIViewController from UIButton's class

这可能对你有用。

class NavigationBarButton: UIButton {


    override func didMoveToWindow() {
        super.didMoveToWindow()

        var viewController: UIViewController? {
            var nextResponder: UIResponder? = self
            repeat {
                nextResponder = nextResponder?.next

                if let viewController = nextResponder as? UIViewController {
                    return viewController
                }

            } while nextResponder != nil

            return nil
        }

        guard let vcViewController = self.viewController else { print("NavigationBarButton view controller could not found"); return }

        print("handle further operations with ViewController of Button")

    }

}

class FirstVC: UIViewController {

    @IBOutlet weak var myButton: NavigationBarButton?


}