开发者

iphone SDK: How to set the initial value of a UIPickerView?

开发者 https://www.devze.com 2022-12-09 13:20 出处:网络
I have a picker view that has a list of numbers to pick from. I want to be able to initialize the control at a particular row. For example, if the user specifies 10 as their defau开发者_如何学编程lt,

I have a picker view that has a list of numbers to pick from. I want to be able to initialize the control at a particular row. For example, if the user specifies 10 as their defau开发者_如何学编程lt, then the control should be automatically positioned at that row when the control is first initialized.

Thanks in advance.


You call selectRow:inComponent:animated: and pass it the index of the row you want selected.

This code causes a UIPickerView to spin through its numbers 0 to 60 before coming to rest on 0.

- (void)viewDidAppear:(BOOL)animated {

    [thePicker selectRow:60 inComponent:0 animated:YES];
    [thePicker reloadComponent:0];
    [thePicker selectRow:60 inComponent:1 animated:YES];
    [thePicker reloadComponent:1];
    [thePicker selectRow:0 inComponent:0 animated:YES];
    [thePicker reloadComponent:0];
    [thePicker selectRow:0 inComponent:1 animated:YES];
    [thePicker reloadComponent:1];
}

In your case, to display row ten you would call something like:

[thePicker selectRow:10 inComponent:0 animated:YES];


What you can do, instead of choosing the row, is to make the pickerview find the value that you want. The way is creating a loop to find it in the array and selecting it:

- (void)viewDidAppear:(BOOL)animated{    
    int i = 0;
    for(NSString* number in arrayName)
    {
        if ([stringValue isEqualToString:number]){
            [pickerViewName selectRow:i inComponent:0 animated:YES ];
        }
        i++;
    }
}


If you are using UITextField with UIPickerView

[self.text_field setInputView:self.picker];

then use this:

self.text_field.text = [_myarray objectAtIndex:10];


Try this it's working for me , just one line of code .

In Objective-C

   [self.picker selectRow:2 inComponent:0 animated:YES];

In Swift

  picker.selectRow(2, inComponent:0, animated:true)

Hope this will help some one .

0

精彩评论

暂无评论...
验证码 换一张
取 消