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

时间:2015-01-08 18:27:11

标签: objective-c swift uiviewcontroller

我有一个允许多个选择的UITableView。我想将选择内容传递到下一个" Q2ViewController"当用户点击rightBarButtonItem" Next"。 注意:我没有使用Storyboard。经过搜索,我还没有找到一个没有使用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)!")
    }
 }

enter image description here

1 个答案:

答案 0 :(得分:0)

您的代码中的任何位置都必须创建“下一个”视图控制器。在App Delegate中或直接在上面显示的视图控制器中。

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

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

您可以使用UITableView的{​​{1}}或类似内容来获取选择,然后在目标视图控制器上调用方法/设置实例变量。

但严重的是,你为什么不使用故事板?