78

I have an iPhone database app that loads a UIPickerView with data from a table. I want to set the selected row to a particular row from the data in another table.

For example: Let's say I have a UIPickerView that is loaded with X number of names of the iPhone users' friends (the number of names is variable; it could be 1 or 1000 and all are entered into the database by the user). The iPhone user has a preference set that their current best friend is TED. I want the UIPickerView to be position to TED when displayed.

Where do I call selectRow?

I tried in viewDidAppear, but it was never called, in titleForRow which caused all kinds of strange behavior. viewDidLoad and viewWillAppear are out of the question, because I don't know what's in the datasource to the picker yet.

4

6 回答 6

142

检索数据后调用它。我不知道你在哪里加载数据,所以这只是应该工作的模型。如果这没有意义,请告诉我您在哪里加载数据,以便我可以在脑海中将其拼凑起来:)

-(void)viewDidLoad
{
    // load data from sql
    // self.someDataArray = DATAFROMSQL
    [picker reloadAllComponents];
    [picker selectRow:0 inComponent:0 animated:YES];
}
于 2009-05-01T20:07:16.607 回答
44

当最初显示 UIPickerView 时需要选择(默认)UIPickerView 项时,存在一个常见问题。问题与事件的顺序有关。从阅读以前的帖子,似乎 [pickerView selectRow:n] 通常在视图控制器 ViewDidLoad 事件中调用。但是,UiPickerView 数据只在 ViewDidLoad 事件之后加载,这意味着 ViewDidLoad 中的任何选择代码都将不起作用。要补救,请将选择代码放在 ViewDidAppear 中;

- (void) viewDidAppear:(BOOL)animated {
[m_pickerView selectRow:nSelectedItem inComponent:0 animated:YES]; }
于 2010-10-21T22:58:59.457 回答
7

将其放置在您初始化UIView包含您UIPickerView的子视图的任何位置:

[myPickerView selectRow:rowWithTedsName inComponent:columnWithNames animated:NO];
于 2009-05-01T20:08:44.543 回答
4

我刚刚发现在 4.3 SDK 的组件加载行为在 iPhone 和 iPad 之间是不同的。在 iPhone 上,我正要在添加到子视图层次结构之前或之后初始化视图之后立即调用 selectRow:。然而,在 iPad 上, selectRow 调用没有产生任何结果。我最终使用了 performSelector:withObject:afterDelay: 调用来等待 0.1 秒,然后再触发 selectRow:inComponent:animated:。这在 iPhone 和 iPad 上产生了可预测的结果。

于 2011-04-25T16:55:41.923 回答
4

对于 Swift,它很简单:

self.picker?.selectRow(0, inComponent: 0, animated: true)
于 2017-07-04T11:30:07.793 回答
0

如果您希望所选行永久突出显示,请使用此

myPickerView.subviews[0].subviews[0].subviews[2].backgroundColor = myPickerView.tintColor;
于 2017-03-26T12:31:38.807 回答