如何使用由变量确定的按钮将a链接到第二个视图控制器?

时间:2015-06-25 18:07:00

标签: swift uipickerview

我创建了一个UIPickerView,里面有一系列服务。我使用didSelectRow在UIPickerView下面显示我选择的服务。这一切都很好并且完美无缺。

我希望选择的服务将我带到另一个名为该服务的视图控制器。例如,在Picker,"咖啡店"中选择了咖啡店。显示在选择器下方,然后单击一个按钮,该按钮将显示一个显示咖啡店给定信息的页面。

@ Pbush25感谢您的快速回复。请你看看我的代码并告诉我哪里出错了,因为我仍然无法让它工作。

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var SelectedService: UILabel!
    @IBAction func Find(sender: AnyObject) {

    }

    @IBOutlet weak var ItemLabel: UILabel!

    var services = ["Cafe","Coffee Shops","Bar","Takeaway","Sunday Roast","Shoe Mender","Craft Shops","Electrical"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // 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.
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{

        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        return services.count   
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{
        return services[row]
    }
}

1 个答案:

答案 0 :(得分:2)

As @JAL said, there is a method for the UIPickerViewDelegate that I belive is didSelectRow or something to that extent, which will give you the index path of the row that was selected. When your button is pressed to go to the next screen, all you have to do in your prepareForSegue method is get the element at that row and use a switch statement to determine which new view controller to activate the segue on based on what value you receive. EDIT: Added code for clarity. //save the picked data to a variable func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { selection = "\(pickerViewData[row])" } //use this variable to decide which segue to take func prepareForSegue(sender: UIStoryboardSegue){ switch selection { case: "Coffee Shops" performSegueWithIdentifier("goToCoffeeShops", sender: self) case: "Some other selection" performSegueWithIdentifier("someOtherSegue", sender: self) } }