2013-02-25 47 views
0

我所試圖做的事:我有的iOS UiPickerView(-Helper)將發送消息

一個ViewController

@implementation ViewController 
@synthesize myPicker; 
@synthesize myPickerHelper; 
@synthesize label; 

#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    myPickerHelper = [[UIPickerViewHelper alloc]initWithUIPickerView:myPicker andNumberOfComponents:4]; 

    [myPickerHelper.valuesForComponent1 addObject:@"TEST1"]; 
    [myPickerHelper.valuesForComponent1 addObject:@"TEST2"]; 
    ; 

    [weightsPicker reloadAllComponents]; 
    [weightsPicker selectRow:0 inComponent:0 animated:YES]; 
    //TODO receive message from picker helper. 
    //label.text = ... set a listner (like that one in java) or what else 
    } 

} 

而且我有一個PickerViewHelper:(它處理的委託和數據源的問題)

@interface UIPickerViewHelper : NSObject <UIPickerViewDelegate, UIPickerViewDataSource, OnPickerViewChangeDelegate> 

@implementation UIPickerViewHelper 
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component 
{ 
    //TODO send message to controller view. 
} 

和協議:

@protocol OnPickerViewChangeDelegate 
@optional 
-(void)onChange:(NSString*)result; 
@end 

我想要的是在我的UiPickerViewHelper類中使用協議方法「onChange」,以便我的標籤(在我的ViewController中)將被通知。 我知道如何解決在Java中,但我不知道如何解決在目標c。

問候

回答

1

UIPickerViewHelper.h

@property (nonatomic, assign) id <OnPickerViewChangeDelegate> delegate 

UIPickerViewHelper.m

@synthesize delegate; 

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component 
{ 
    //TODO send message to controller view. 
    [self.delegate onChange:[NSString stringWithFormat:@"Selected row %d", row]]; 
} 

ViewController.m

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    myPickerHelper = [[UIPickerViewHelper alloc]initWithUIPickerView:myPicker andNumberOfComponents:4]; 
    myPickerHelper.delegate = self; 

    ... 
} 

-(void)onChange:(NSString*)result { 

    NSLog(@"Here is the result: %@", result); 
    label.text = result; 
} 
+0

OK !!!這樣可行!但我不明白爲什麼...爲什麼視圖控制器知道(或可以覆蓋)onchange方法? – 2013-02-25 15:11:38

+0

由於視圖控制器符合'OnPickerViewChangeDelegate'協議,這意味着視圖控制器必須實現該方法。它不是壓倒性的,它只是在實施它。 – 2013-02-25 15:16:52

+0

@ user2075873請將我的答案標記爲已接受(複選標記),如果它幫助您:) – 2013-02-25 15:35:02

0

沒有UIPickerview委託方法進行更改。 因爲它會停在任意位置和

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

方法將被調用,因此,如果用戶退出選擇器停止動畫/軋製前... 隱藏的UIPickerView必須調用最後選定的值uipicker方法同時滾動/動畫。

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component 
    { 
    if(delegate respondsToSelector:@selector(onChange:)){ 
     [delegate onChange:row];//return the index of row selected 
    } 
    }