2012-11-29 216 views
2

我試圖將UIPicker添加到UITextView,當它選擇爲選擇年齡時。我發現了一個以前的thread,並進行了修改以實現代碼,但我無法使其正常工作。當我構建程序時,選擇器顯示出來,但沒有任何值。任何想法,我做錯了什麼?另外,我得到兩個黃色的錯誤在這裏說:「分配給從不兼容的類型「的ViewController * const的__strong‘身份證’」在這裏:將UI Picker添加到UITextView

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]; 
} 

回答

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 
+0

真。我在亂搞,忘了改回來。謝謝。我會編輯它。 – user1681673

+0

你在實現'pickerView:titleForRow:forComponent:'方法嗎? – tkanzakic

+0

編號是這樣的:ageTextField.text = [ageArray objectAtIndex:component]; ? – user1681673