IOS newb with web programming background.
In html I am used to drop down boxes with states (i.e. AK,AL,CA,MA,NY,NJ, etc.) using the select statement. What is the equivalent syntax using UIpickerview? I know how to put the picker view in storyboard but don't know how to get all the states to show up in the picker and then capture the selected state.
Thanks in advance for any suggestions.
As you have put the pickerView in StoryBoard, create an IBOutlet in your ViewController, and one array of states
@IBOutlet weak var myPicker: UIPickerView!
var states = ["state1", "state2","state3"]
var selectedState = ""
Set the delegate and data source of your pickerView
override func viewDidLoad() {
super.viewDidLoad()
myPicker.dataSource = self
myPicker.delegate = self
}
Call the delegate methods:
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return states.count
}
To place the data in the picker:
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return states[row]
}
And to capture the selected state:
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedState = states[row]
}
EDIT for ObjC
Creating the outlet and setting the delegate and datasource for pickerView are quite similar: Here are the delegate methods:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return ([states count]);
}
To place the data in the picker:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return ([states objectAtIndex: row]);
}
And to capture the selected state:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
selectedState = ([states objectAtIndex:row]);
}