我对Xcode比较陌生,我需要一些帮助。因此,我的视图有2个按钮(它有更多的按钮,但为简单起见,比方说2),它们都连接到一个IBAction。按下每个按钮时,Picker会显示加载数组,具体取决于按下哪个按钮。我希望按钮的标题与用户在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];
}
答案 0 :(得分: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];
}
答案 1 :(得分: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];
}