How do I add rows to UIPickerView from UIAlertController

608 views Asked by At

I have a UIPickerView that gets its data from an array that is defined in

friends = [NSArray arrayWithObjects: @"jim", @"joe", @"anne", nil];

I have a button under the picker that is supposed to add new friends to the picker. When the button is pressed a UIAlertController pops up and the user can enter the new friends name. I can save the text as a string but I can't add it to the array. I've also tried using NSMutableArray's.

I'm new to this so all input would be great. I've looked at similar questions for help but nothing has worked.

Thanks!

1

There are 1 answers

1
Karlo A. López On BEST ANSWER

Ok so I will try to explain this:

You declare a NSMutbleArray, you can't expect to use a NSArray because is not mutable, and you need to modify the content.

    NSMutableArray *array;
    UIAlertController * view;
    @implementation ViewController


    - (void)viewDidLoad {
        [super viewDidLoad];
        NSArray* friends = [NSArray arrayWithObjects: @"jim", @"joe", @"anne", nil];
        array = [NSMutableArray arrayWithArray:friends];
// I added a UIPickerView in the StoryBoard, connected it to a property and the delegates and datasources.
        self.pickerView.delegate = self;
    }

Then you declare dataSource of UIPickerView:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

    return 1;

}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

    return array.count;

}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    return array[row];

}

So, then you present your UIAlertController, in this case I will dismiss it in the Return of the TextView.

//This is an action connected to the button which will present the ActionController
- (IBAction)addFriend:(id)sender {



    view =   [UIAlertController alertControllerWithTitle:@"Add Friend" message:@"Write the friend to add"preferredStyle:UIAlertControllerStyleAlert];

    [view addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Friend";
        textField.delegate = self;
        textField.tag = 01;
    }];

    [self presentViewController:view animated:YES completion:nil];

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    if(textField.tag == 01){

        [array insertObject:textField.text  atIndex:array.count];
        [view dismissViewControllerAnimated:YES completion:^{
            [self.pickerView reloadAllComponents];
        }];

        return YES;

    }

    return YES;

}

This is more or less what you can do, I was the most specific I could be because you said you are a begginer.

Hope it Helps.