简体   繁体   中英

Iphone:Split a string seperated by comma and print each in row of pickerview

I got a string as mild,medium,hot .I split the string with comma as separator.I need to print it in a pickerView too.
I used the following code and got List count as 3 successfully.

    NSString *spList=[mdict objectForKey:@"spicinesstype"];
    NSArray *list = [spList componentsSeparatedByString:@","];
    NSLog(@"List count:%d",[list count]);
    return [list count];

But how could I display all 3 items in pickerview

You should set your class as the delegate of the picker view, Then implement these 3 delegate methods for your picker

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
    return [array count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [array objectAtIndex:row];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
    return 1;
}

First you need to implement UIPickerViewDelegate and UIPickerViewDataSource by putting them on the end of the @interface line of the header file of your view controller.

Like this: @interface MyViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>

Next you need to set your view controller as the delegate and data source of you picker view. You can either do this in the - (void)viewDidLoad method of your view controller by adding the lines:

myPickerView.delegate = self;
myPickerView.dataSource = self;

Or you can link it up in Interface Builder if you are using that.

Then you need to implement these delegate methods in your View Controller source file.

 (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    // whatever you want to happen when a row is selected.
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [list count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    return [list objectAtIndex:row];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM