用户从xcode中的多组件选择器中选择特定值后,如何显示特定消息/警报?

问题描述

用户从双component picker中选择2个值时,我试图显示一条消息。

如果用户选择的是“高烧”和“强咳”,请使用警报视图显示一条消息,指出:“您应该进行PCR测试”。

如果用户选择的是“高烧”和“中咳”或“中烧”和“强咳”,则显示一条消息,指出:“这只是普通流感”。

在所有其他可能的选择的情况下,显示一条消息:“放松……不用担心!”

这是下面的代码

#import "FirstViewController.h"
#define kFeverComponent 0
#define kCoughComponent 1

@interface FirstViewController ()
@property (strong,nonatomic) NSArray *feverTypes;
@property (strong,nonatomic) NSArray *coughTypes;
@property (weak,nonatomic) IBOutlet UIPickerView *dependentPicker;

@end

@implementation FirstViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   self.feverTypes = @[@"High Fever",@"Medium Fever",@"No Fever"];
   self.coughTypes = @[@"Strong Cough",@"Medium Cough",@"No Cough"];
}
- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
}
- (IBAction)symptomsButtonpressed:(id)sender {
   NSInteger feverRow = [self.dependentPicker selectedRowInComponent: kFeverComponent];
   NSInteger coughRow = [self.dependentPicker selectedRowInComponent: kCoughComponent];
   Nsstring *fever = self.feverTypes[feverRow];
   Nsstring *cough = self.coughTypes[coughRow];
   Nsstring *message = [[Nsstring alloc] initWithFormat:
     @"You chose %@ and %@.",fever,cough];
   UIAlertController *alert =
     [UIAlertController
       alertControllerWithTitle:@"Thank you for choosing" message:message 
       preferredStyle:UIAlertControllerStyleAlert];
   UIAlertAction *action = [UIAlertAction actionWithTitle:@"Okay" 
     style:UIAlertActionStyleDefault handler:nil];
   [alert addAction:action];
   [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark -
#pragma mark Picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
   return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: 
   (NSInteger)component {
   if (component == kCoughComponent) {
     return [self.coughTypes count];
} else {
    return [self.coughTypes count];
}
}

#pragma mark Picker Delegate Methods
- (Nsstring *)pickerView:(UIPickerView *)pickerView
    titleForRow:(NSInteger)row
    forComponent:(NSInteger)component {
    if (component == kCoughComponent) {
      return self.coughTypes[row];
    } else {
      return self.feverTypes[row];
}
}

@end

解决方法

您需要实现pickerview:didSelectRow:inComponent委托方法。因此,通过将其添加到接口定义(例如

)中,使您的类遵守UIPickerViewDelegate协议
@interface FirstViewController () < UIPickerViewDelegate >

然后执行例如

- ( void ) pickerView:( UIPickerView * ) pickerView
         didSelectRow:( NSInteger      ) row
          inComponent:( NSInteger      ) component
{
    // logic here e.g.
    NSInteger fever = [pickerView selectedRowInComponent:kCoughComponent];
    NSInteger cough = [pickerView selectedRowInComponent:kFeverComponent];
    NSString * msg;

    if ( fever >= threshold && cough >= threshold )
    {
       msg = @"Seek help";
    }
    else
    {
       msg = @"All fine";
    }

    // Show alert with msg
}