使用 Swift 中的 UIBarButtonItem 将数据传递给下一个 ViewController

Pass Data to next ViewController Using UIBarButtonItem in Swift

我有一个允许多选的 UITableView。当用户单击 rightBarButtonItem "Next" 时,我想将选择传递给下一个 "Q2ViewController"。 注意:我没有使用故事板。经过搜索,我还没有找到不使用storybaord的解决方案。

var options = ["breakfast", "lunch", "dinner", "dessert"]
    var selected = -1

override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Q1View"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .Done, target: self, action: "didTapNext:")
        self.tableView.allowsMultipleSelection = true

        var nib = UINib(nibName: "OptionCell", bundle: nil)
        tableView?.registerNib(nib, forCellReuseIdentifier: "OptionCellIdentifier")
}

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.options.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("OptionCellIdentifier", forIndexPath: indexPath) as OptionCell
        cell.textLabel?.text = self.options[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("You selected cell #\(indexPath.row)!")
    }
 }

代码中的任何地方都必须创建 "next" 视图控制器。在您的 App Delegate 中或直接在上面显示的视图控制器中。

如果您在上述控制器之外创建视图控制器,则必须向上述控制器传递对目标视图控制器的引用。

如果您在上面的视图控制器中创建视图控制器,请在实例变量中保存对它的引用。 或者创建一个方法,在按下 "Next" 按钮时创建 VC 并将 VC 推送到导航控制器。

您可以使用 UITableViewindexPathsForSelectedRows() 或类似方法来获取选择,然后在目标视图控制器上调用 method/set 实例变量。

但说真的,你为什么不使用故事板呢?