Search code examples
iosobjective-cuitextviewuipickerview

Using UIPickerView to populate UITextView within a UIViewController .xib framework


Let me preface by saying that I am completely new to programming. I have also done a bunch of searching on this issue and haven't found an answer that seems to address exactly what I am doing.

The result I am looking for is a text field that can be populated by the user by using a pickerView. After putting a UITextView box in the .xib file I am not sure how make it call a pickerView when tapped and then populate from that picker view.

Thank you for any help given. Let me know if I need to clarify more.


Solution

  • Create a UIPickerView and set it as the inputView property of your UITextView. Then, register your class for the dataSource/delegate of the UIPickerView to populate it and know when it has changed selection. Below is a simple solution for a picker with a single component.

    SomeViewController.h:

    @interface SomeViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
    {
        UIPickerView *picker;
        NSArray *dataSource;
    }
    

    SomeViewController.m:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        picker = [[UIPickerView alloc] init];
        picker.dataSource = self;
        picker.delegate = self;
    
        myTextView.inputView = picker;
    }
    
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
        return 1;
    }
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        return [dataSource count];
    }
    
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    {
        return [dataSource objectAtIndex:row];
    }
    
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        [myTextView setText:[dataSource objectAtIndex:row]];
    }