2

I'm trying to add a UIPickerto a UITextViewwhen it is selected to choose an age. 我找到了一个以前的线程并实现了代码,但我无法让它正常工作。当我构建程序时,选择器会出现,但其中没有值。关于我做错了什么的任何想法?另外,我在这里收到两个黄色错误,说“从不兼容的类型'ViewController *const __strong'分配给'id'”:

pickerView.delegate = self;
pickerView.dataSource = self;

谢谢你。

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextField *ageTextField;

@end

@implementation ViewController
@synthesize ageTextField;

- (void)viewDidLoad
{
    [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

    UIPickerView *pickerView =[[UIPickerView alloc]init];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.showsSelectionIndicator=YES;
    ageTextField.inputView=pickerView;
}

- (void)pickerView:(UIPickerView *)PickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component {

    NSMutableArray *ageArray = [[NSMutableArray alloc]init];

    [ageArray addObject:@"1"];
    [ageArray addObject:@"2"];
    [ageArray addObject:@"3"];
    [ageArray addObject:@"4"];

    ageTextField.text=[ageArray objectAtIndex:row];
}
4

1 回答 1

3
@interface ViewController () <UIPickerViewDataSource, UIPickerViewDelegate>

@property (strong, nonatomic) UIPickerView *pickerView;
@property (strong, nonatomic) NSArray *pickerElements;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.pickerView = [[UIPickerView alloc] init];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    self.pickerView.showsSelectionIndicator = YES;
    self.ageTextField.inputView = self.pickerView;

    self.pickerElements = @[@"text1", @"text2", @"text3", @"text4"];
    [self pickerView:self.pickerView
        didSelectRow:0
         inComponent:0];
}

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

- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
     return [self.pickerElements count];
}

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

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.ageTextField.text = [self.pickerElements objectAtIndex:row];
}

@end
于 2012-11-29T19:25:44.027 回答