2014-01-25 85 views
0

我對Xcode比較陌生,我需要一些幫助。所以,我的觀點有2個按鈕(它有更多的按鈕,但爲了簡單起見,我們假設2)都連接到一個IBAction。當按下每個按鈕時,拾取器會顯示根據按下哪個按鈕加載數組。我希望按鈕的標題與用戶在PickerView中選擇的內容相匹配。根據標籤更改特定命令按鈕的標題

我知道我必須修改pickerView:didSelectRow方法中的一些代碼,但我不知道該怎麼做。現在它的工作方式是,不管我點擊哪個按鈕(我應該注意正確的數組加載,以便該部分正常工作),帶有標籤「0」的按鈕會被選中的Picker行的內容修改。所以我需要修改SELECTED標籤上的按鈕。

我的頭文件是:

@interface XYZSecondViewController : UIViewController <UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate> 

@property (strong, nonatomic) IBOutlet UIPickerView *myPicker; 
@property (strong, nonatomic) IBOutlet UIButton *myButton; 

- (IBAction)myButton:(id)sender; 

@end 

我實現文件:

#import "XYZSecondViewController.h" 
@interface XYZSecondViewController() 
    @property (strong,nonatomic) NSArray *myArray1; 
    @property (strong,nonatomic) NSArray *myArray2; 
    @property (strong,nonatomic) NSArray *chosenArray; 
@end 

@implementation XYZSecondViewController 
@synthesize myButton, myPicker; 

- (IBAction)myButton:(id)sender 
{ 
    switch ([sender tag]) 
    { 
     case 0: 
      self.chosenArray = self.myArray1; 
      break; 
     case 1: 
      self.chosenArray = self.myArray2; 
      break; 
    } 
    [self.myPicker reloadAllComponents]; 
} 

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

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component 
{ 
     [myButton setTitle:[chosenArray objectAtIndex:row] forState:UIControlStateNormal]; 
} 

回答

3

你可以跟蹤目前拍了拍按鈕的標籤。

事情是這樣的:

@property (nonatomic) NSInteger tagLastTappedButton; 

... 

- (IBAction)myButton:(id)sender 
{ 
    tagLastTappedButton = sender.tag; 
    ... 
} 

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component 
{ 
     UIButton *buttonTapped = (UIButton *)[self.view viewWithTag:tagLastTappedButton]; 
    [buttonTapped setTitle:[chosenArray objectAtIndex:row] forState:UIControlStateNormal]; 
} 
0

拿你一個整數頭:

int flag; 

修改您切換情況:

switch ([sender tag]) 
    { 
     case 0: 
      self.chosenArray = self.myArray1; 
      flag=0; 
      break; 
     case 1: 
      self.chosenArray = self.myArray2; 
      flag=1; 
      break; 
    } 

,並在您didSelectRow作出IF聲明像:

if (flag==0) { 
    [myButton1 setTitle:[chosenArray objectAtIndex:row] forState:UIControlStateNormal]; 
}else{ 
    [myButton2 setTitle:[chosenArray objectAtIndex:row] forState:UIControlStateNormal]; 
} 
+0

我認爲這是行不通的,因爲我沒有「myButton1」,「myButton2」等。我只有多個按鈕,這些按鈕都被稱爲「myButton」,但它們的Tag屬性不同。我對麼? – kkrapic

+0

但在你的問題中,你說我有兩個按鈕,所以你必須拿兩個獨立的IBOutlets,並分別連接它們。 – Ajay

+0

不,但我說「哪一個都連接到一個IBAction」。我只是爲每個按鈕設置不同的標籤值。不管怎樣,小小的誤解:) – kkrapic