繁体   English   中英

iOS:获取“UIButton”的“UIViewController”

[英]iOS: Get 'UIViewController' of 'UIButton'

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

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?


}

结果:
NavigationBarButton 视图 controller 找不到

有没有其他方法,在不更新 UIViewController 的情况下,我可以查看 controller 参考 ZA4F6654A77BFEC18184BC 的子 class 中的 controller 任何其他 UIButton 方法都可以在这里帮助我,在这里我可以查看按钮的 controller。

类似的SO阙。 但对这个问题没有用: 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?


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM