由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [_。AppDelegate add:]:无法识别的选择器

时间:2016-08-28 23:52:42

标签: ios swift appdelegate nsexception

我创建了一个名为Main.storyboard的故事板,并创建了一个带故事板ID“addBtnVC”的AddBtnViewController。在App Delegate中,我以编程方式初始化了一个带有三个视图控制器的标签栏。对于其中一个标签栏视图控制器,我创建了一个添加按钮,该按钮将以编程方式转换到AddBtnViewController。但是,我收到了这个错误:

uncaught exception 'NSInvalidArgumentException', reason: '-[_.AppDelegate add:]: unrecognized selector sent to instance 0x7f91cb422a30'

我的代码:

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
         //Make add btn for View Controller 1 of Navigation Bar
         let addBtn = UIButton(frame: CGRectMake(0, 0, 30, 30))
         addBtn.addTarget(self, action: #selector(ViewController1.add), forControlEvents: .TouchUpInside)

         let rightBarButton = UIBarButtonItem()
         rightBarButton.customView = addBtn
         NavController.navigationBar.topItem?.rightBarButtonItem = rightBarButton

         return true
    }
}

class ViewController1: UIViewController {
    let addBtnVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("addBtnVC")

    func add(sender: UIButton!) {
        if let addBtnVC = storyboard!.instantiateViewControllerWithIdentifier("addBtnVC") as? AddBtnViewController {
            presentViewController(addBtnVC, animated: true, completion: nil)
        }
    }
}

如何解决此错误?

后人:

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
         let VC1 = UIViewController()

         //Make add btn for View Controller 1 of Navigation Bar
         let addBtn = UIButton(frame: CGRectMake(0, 0, 30, 30))
         addBtn.addTarget(VC1, action: #selector(VC1.add(_:)), forControlEvents: .TouchUpInside)

         let rightBarButton = UIBarButtonItem()
         rightBarButton.customView = addBtn
         NavController.navigationBar.topItem?.rightBarButtonItem = rightBarButton

         return true
    }
}

class ViewController1: UIViewController {
    let addBtnVC:AddButtonViewController = AddButtonViewController()

    func add(sender: UIButton!) {
        let navController = UINavigationController(rootViewController: addBtnVC)
        navController.navigationBar.tintColor = colorPalette.red
        self.presentViewController(navController, animated: true, completion: nil)
    }

}

1 个答案:

答案 0 :(得分:3)

您将按钮操作的目标设置为self,表示AppDelegate类。

按钮操作的选择器必须与目标位于同一个类中,但它不是。这就是错误信息所说的内容。此外,选择器的签名是错误的,因为它需要一个参数。