【问题标题】:Swift 4 @IBAction UIButton action not being called correctlySwift 4 @IBAction UIButton 动作没有被正确调用
【发布时间】:2019-07-24 13:16:13
【问题描述】:

我知道这个问题在这个网站上经常被问到,但是我看过的每个问题都有不同的答案,我每个人都试过了。

我有一个 UIButton 放在我的情节提要中,并将它连接到视图控制器中的 @IBAction。每次点击按钮,都会报错-[UIViewController openAlert]: unrecognized selector sent to instance

该函数没有参数(我尝试使用 sender 参数,它调用 openAlertWithSender 而不是 openAlert(sender:)),我认为将按钮连接到类顶部的变量会起作用,但它给了我一个新的错误:This class is not key value coding-compliant

我确保按钮正确连接到情节提要中的功能,并确保在视图中启用了用户交互。

我已尝试以编程方式构建按钮,但它根本不会出现在屏幕上。

无论我做什么,我似乎都无法让这个按钮工作。

我的代码:

class OfflineViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

    // Hide the navigation bar
        navigationController?.setNavigationBarHidden(true, animated: animated)

        NetworkHandler.shared.addListener(listener: self)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // Show the navigation bar
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)

        NetworkHandler.shared.removeListener(listener: self)

    }

    private func showMainController() -> Void {
        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "NetworkAvailable", sender: self)
        }
    }

    @IBAction func openAlert() {
        let alert = UIAlertController(title: "Clicked", message: "You have clicked on the button", preferredStyle: .alert)

        self.present(alert, animated: true, completion: nil)
    }


}

感谢任何帮助。

【问题讨论】:

    标签: ios swift uibutton ibaction


    【解决方案1】:

    首先确保将 IB 中的类名分配给 vc OfflineViewController

    第二次添加这个方法

    @IBAction func printMessage(_ sender:UIButton) { } 
    

    而不是openAlert,似乎您在将其命名为printMessage 后更改了它的名称,并且IB 封装了不再存在的旧名称,因此崩溃了

    注意:storyboard 是一个幕后的 xml 文件,因此每个出口/动作名称都会一直存在,直到您更改它为止,并且在编译时没有错误机制可以告诉您

    【讨论】:

    • 我以 printMessage 为例,但 openAlert 是连接到按钮的实际功能。故事板还说此屏幕已连接到 vc OfflineViewController。
    • 点击ib中的按钮,看看它是否连接到任何其他方法
    • 不是。它只连接到函数openAlert。没有其他变量,没有其他函数,什么都没有。
    • 你能把签名改成@IBAction func openAlert(_ sender:UIButton) { }
    • 我刚试了一下,改了之后重新连接,还是一样的崩溃。我还需要连接 IBOutlet 变量吗? --Edit-- 这样做会导致上面的错误(not key value coding-compliant
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多