簡體   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