Last active
August 8, 2016 10:20
-
-
Save mosluce/84fc9fbb7f2a37d78fd5cd1c20e2b745 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // ViewController.swift | |
| // SwiftPicker | |
| // | |
| // Created by 默司 on 2016/8/8. | |
| // Copyright © 2016年 默司. All rights reserved. | |
| // | |
| import UIKit | |
| class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { | |
| @IBOutlet weak var textField: UITextField! | |
| let picker = UIPickerView() | |
| let options = ["First", "Second", "Third"] | |
| let optionsChild = [["A", "B", "C", "D"], ["D", "E", "F"], ["X", "Y", "Z", "BlahBlah"]] | |
| var text = "" | |
| var textChild = "" | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| // Do any additional setup after loading the view, typically from a nib. | |
| textField.inputView = picker | |
| picker.delegate = self | |
| picker.dataSource = self | |
| picker.selectRow(0, inComponent: 0, animated: false) | |
| picker.selectRow(0, inComponent: 1, animated: false) | |
| selectAndTrigger(row: 0, component: 0) | |
| selectAndTrigger(row: 0, component: 1) | |
| } | |
| func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { | |
| if component == 0 { | |
| return options.count | |
| } else { | |
| return optionsChild[pickerView.selectedRowInComponent(0)].count | |
| } | |
| } | |
| func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { | |
| return 2 | |
| } | |
| func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { | |
| if component == 0 { | |
| return options[row] | |
| } else { | |
| return optionsChild[pickerView.selectedRowInComponent(0)][row] | |
| } | |
| } | |
| func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { | |
| if component == 0 { | |
| text = options[row] | |
| pickerView.reloadComponent(1) | |
| pickerView.selectRow(0, inComponent: 1, animated: true) | |
| self.pickerView(pickerView, didSelectRow: 0, inComponent: 1) | |
| } else { | |
| textChild = optionsChild[pickerView.selectedRowInComponent(0)][row] | |
| } | |
| textField.text = "\(text) - \(textChild)" | |
| } | |
| func selectAndTrigger(row row: Int, component: Int) { | |
| pickerView(picker, didSelectRow: row, inComponent: component) | |
| } | |
| override func didReceiveMemoryWarning() { | |
| super.didReceiveMemoryWarning() | |
| // Dispose of any resources that can be recreated. | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment