我怎样才能得到一个导航栏按钮来继续?

How can I get a navigation bar button to segue?

我有一个指向 UIViewController 的 UINavigationController。在那个 UIViewController 中,我希望 navigationitem 的右键是一个 .Add UIBarButtonItem,它会转到另一个名为 "nextScene".

的场景

据我了解,如果我想以编程方式创建此 segue,我需要让操作成为 "performSegueWithidentifier" 方法。这是我拥有的:

let plusButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "<strong>performSegueWithIdentifier:</strong>")<br> self.navigationItem.setRightBarButtonItem(plusButton, animated: true)

进入另一个名为 "nextScene" 的场景的正确语法是什么?我的 performSegueWithidentifier 方法应该如何处理这个问题?

编辑: 出现以下错误:无法识别的选择器发送到实例 ... 2015-08-06 07:57:18.534 ..[...] *** 由于未捕获的异常 'NSInvalidArgumentException',正在终止应用程序,原因:' -[... goToSegue:]: 无法识别的选择器发送到实例....

这是我用于 segue 的代码:

let plusButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "goToSegue:")`

self.navigationItem.setRightBarButtonItem(plusButton, animated: true) }

func goToSegue() {
    performSegueWithIdentifier("segueName", sender: self)
}

您只需控制并从您的 UIBarButtonItem 拖动到故事板中的 UIViewController(或其他类型的控制器)。

如果您想通过代码来完成,您需要在目标 class 中使用可以处理它的方法来备份您的操作调用。 performSegueWithIdentifier 是视图控制器的默认方法,因此我会调用另一个函数,然后调用 performSegueWithIdentifier,如下所示:

let plusButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "plusBttnTouched:")

func plusBttnTouched(sender: UIBarButtonItem) {

    performSegueWithIdentifier(identifier: "segueNameHere", sender: self)

}

这是更新后的代码示例:

故事板:

代码:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Create bar button item

    let plusButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: Selector("plusBttnTouched:"))

    self.navigationItem.rightBarButtonItems = [plusButton]

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: - Actions

func plusBttnTouched(sender: UIBarButtonItem) {

    dispatch_async(dispatch_get_main_queue(), { () -> Void in

        self.performSegueWithIdentifier("plusViewController", sender: self)
    })

}

}

在您的方法参数中使用发送者允许您在您的方法中访问定义类型的实例。当您将 : 添加到选择器的末尾时,您说您想要这个,这不是必需的。

  1. UIViewController 之间创建 segue(右键单击 firstViewController 并将其拖动到 secondviewcontroller

  1. 为那个 segue
  2. 提供标识符名称

  1. 用那个 segue 名字执行 segue

现在为了使用 UIBarButtonItem 执行 segue,将 viewDidLoad 方法中的以下代码添加到 firstViewController

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "navigateToNextViewController")
    // Do any additional setup after loading the view, typically from a nib.
}

现在创建 navigateToNextViewController 方法并从该方法执行 segue

func navigateToNextViewController(){
    self.performSegueWithIdentifier("goNext", sender: self)
}