I have a problem with my UIPickerView.
I have 3 values in it EU AP and NA.
When I start the app EU seems to be selected but when I make a NSLog(@"%@", [regions objectAtIndex:row]); I only get back (null),
now when I touch the UIPickerView the EU value is selected and I get "EU" back from a NSLog.
My question is:
How can I define a default value which is selected (not only the label) when the user only starts the app and touches nothing.
Edit: Here is my code to get the selected item:
#pragma mark -
#pragma mark PickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return [regions count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return [regions objectAtIndex:row];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
selectedRegion = [[NSString alloc] initWithFormat:
@"%@", [regions objectAtIndex:row]];
NSLog(@"%@", selectedRegion);
}
TL:DR version:
Either you didn’t set your picker to select the row (which you say you seem to have done but anyhow):
OR you didn’t use the the following method to get the selected item from your picker
This will get the selected row as Integer from your picker and do as you please with it.
This should do the trick for yah. Good luck.
Anyhow read the ref:
https://developer.apple.com/documentation/uikit/uipickerview
EDIT:
An example of manually setting and getting of a selected row in a UIPickerView:
the .h file:
the .m file:
EDIT for Swift solution (Source: Dan Beaulieu’s answer)
Define an Outlet:
Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:
If you inspect the Swift 2.0 framework you’ll see .selectRow defined as:
option clicking .selectRow in Xcode displays the following: