UIPickerView“didSelectRow”选项,带有导致网址

时间:2016-07-02 18:17:17

标签: ios swift url uipickerview nsurl

我有一个选择器设置,并希望让用户做出选择,然后点击一个通向网址的按钮。这是我到目前为止: -

class PickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    @IBOutlet weak var picker: UIPickerView!
    @IBOutlet weak var label: UILabel!

    var url = NSURL(string: "http://www.google.com")
    var pickerData: [String] = [String]()
    var pickerSites: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.picker.delegate = self
        self.picker.delegate = self

        pickerData = ["Google", "Facebook"]
        pickerSites = ["http://www.google.com", "http://www.facebook.com"]
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

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

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

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        label.text = pickerSites[row]
    }

    siteBtn.addTarget(self, action: "didTapSite", forControlEvents: .TouchUpInside)

    @IBAction func sitesBtn(sender: AnyObject) {
        UIApplication.shared().openURL(NSURL(string: "http://www.google.com")!)
    }

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

我已将“siteBtn”连接到屏幕上的按钮。选择器和文本标签工作正常,直到我添加按钮的代码。我不确定我是否将按钮代码放在正确的位置。我知道我需要按钮来连接选择器“didSelectRow”,并且“pickerData”列表需要与“pickerSites”列表相关联,但我被卡住了。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

这是您需要的最小设置。随时可以询问是否有任何不清楚的地方:

// outlet to the pickerview
@IBOutlet weak var picker: UIPickerView!

// datasource
let pickerData = ["Google", "Facebook"]
let pickerSites = ["http://www.google.com", "http://www.facebook.com"]

// pickerview datasource methods
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

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

// pickerview delegate method
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}

// ibaction for button tap
@IBAction func goToURLButtonTapped(sender: UIButton) {
    let selectedSite = pickerSites[picker.selectedRowInComponent(0)]
    UIApplication.sharedApplication().openURL(NSURL(string: selectedSite)!)
}