Select row After UIPickerView is loaded

余生颓废 提交于 2019-11-28 04:16:11

Call it after you retrieve the data. I don't know where you load the data so this is just a mockup of what should work. If this doesn't make sense, let me know where you are loading data so I can piece it together in my head :)

-(void)viewDidLoad
{
    // load data from sql
    // self.someDataArray = DATAFROMSQL
    [picker reloadAllComponents];
    [picker selectRow:0 inComponent:0 animated:YES];
}

There is a common issue when a (default) UIPickerView item needs to be selected when the UIPickerView is initially shown. The problem is related to the sequence of events. From reading previous posts, it seems that the [pickerView selectRow:n] is normally called in the view controllers ViewDidLoad event. However, the UiPickerView data is only loaded after the ViewDidLoad event, which means any selection code in ViewDidLoad will have no effect. To remedy, place the selection code in ViewDidAppear;

- (void) viewDidAppear:(BOOL)animated {
[m_pickerView selectRow:nSelectedItem inComponent:0 animated:YES]; }

Place this wherever you initialize the UIView that contains your UIPickerView as a subview:

[myPickerView selectRow:rowWithTedsName inComponent:columnWithNames animated:NO];

I have just found that on the 4.3 SDK's the component loading behaviors are different between the iPhone and the iPad. On the iPhone, I was about to invoke selectRow: right after initializing the view before or after adding to the subview hierarchy. On iPad however, the selectRow call yielded no results. I wound up using a performSelector:withObject:afterDelay: call to wait 0.1 seconds before firing selectRow:inComponent:animated:. This had predictable results on the iPhone and iPad.

Er. Vihar

For Swift it's simply:

self.picker?.selectRow(0, inComponent: 0, animated: true)

If you want the selected row permanently highlighted use this

myPickerView.subviews[0].subviews[0].subviews[2].backgroundColor = myPickerView.tintColor;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!