web-dev-qa-db-fra.com

Comment définir une valeur par défaut d'un UIPickerView

J'ai un problème avec mon UIPickerView. J'ai 3 valeurs en EU AP et NA. Quand je lance l'application, EU semble être sélectionné mais quand je crée une NSLog(@"%@", [regions objectAtIndex:row]);, je ne récupère que (null), lorsque je touche UIPickerView, la valeur EU est sélectionnée et j’obtiens "EU" retour d'un NSLog.

Ma question est:

Comment définir une valeur par défaut qui est sélectionnée (pas uniquement l'étiquette) lorsque l'utilisateur ne lance que l'application et ne touche à rien.

Edit: Voici mon code pour obtenir l'élément sélectionné:

#pragma mark -
#pragma mark PickerView DataSource

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return [regions count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [regions objectAtIndex:row];
}

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{

                selectedRegion = [[NSString alloc] initWithFormat:
                              @"%@", [regions objectAtIndex:row]];
    NSLog(@"%@", selectedRegion);


}
61
Chris

TL: version DR:

//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)

Soit vous n’avez pas paramétré votre sélecteur pour sélectionner la rangée (ce que vous semblez avoir fait mais de toute façon):

- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated

OU vous n'avez pas utilisé la méthode suivante pour extraire l'élément sélectionné de votre sélecteur

- (NSInteger)selectedRowInComponent:(NSInteger)component

La ligne sélectionnée en tant qu'entier sera alors sélectionnée à partir de votre sélecteur et fera ce que vous voudrez. Cela devrait faire l'affaire pour yah. Bonne chance.

Quoi qu'il en soit, lisez le ref: https://developer.Apple.com/documentation/uikit/uipickerview


MODIFIER:

Exemple de définition et d’obtention manuelle d’une ligne sélectionnée dans un UIPickerView:

le fichier .h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *picker;
    NSMutableArray *source;
}

@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;

-(void)pressed;

@end

le fichier .m:

#import "ViewController.h"

@interface ViewController ()

@end
@implementation ViewController

@synthesize picker;
@synthesize source;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.view.backgroundColor = [UIColor yellowColor];

    self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];

    UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
    [pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
    pressme.backgroundColor = [UIColor lightGrayColor];
    [pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pressme];

    self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
    self.picker.delegate = self;
    self.picker.dataSource = self;
    [self.view addSubview:self.picker];

    //This is how you manually SET(!!) a selection!
    [self.picker selectRow:2 inComponent:0 animated:YES];
}

//logs the current selection of the picker manually
-(void)pressed
{
    //This is how you manually GET(!!) a selection
    int row = [self.picker selectedRowInComponent:0];

    NSLog(@"%@", [source objectAtIndex:row]);
}

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return [source count];
}

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

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
//    NSLog(@"%@", [source objectAtIndex:row]);
}

@end

EDIT for Swift (Source: réponse de Dan Beaulieu)

Définir un point de vente:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Ensuite, dans votre viewWillAppear ou votre viewDidLoad , par exemple, vous pouvez utiliser les éléments suivants:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

Si vous inspectez le framework Swift 2.0), vous verrez que .selectRow est défini comme suit:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

L'option en cliquant sur .selectRow dans Xcode affiche les éléments suivants:

91
Totumus Maximus

Ceci est comment définir une valeur par défaut d'un UIPickerView

[self.picker selectRow:4 inComponent:0 animated:YES];
18
Hardik Darji

Solution rapide:

Définir un point de vente:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Ensuite, dans votre viewWillAppear ou votre viewDidLoad , par exemple, vous pouvez utiliser le suivant:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

Si vous inspectez le framework Swift 2.0, vous verrez .selectRow défini comme:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

en cliquant sur l'option .selectRow dans Xcode affiche les éléments suivants:

enter image description here

8
Dan Beaulieu

Moi aussi j'ai eu ce problème. Mais apparemment, il y a un problème d'ordre des appels de méthode. Vous devez appeler:

[self.picker selectRow:2 inComponent:0 animated:YES];

après appelant

[self.view addSubview:self.picker];
6
user4833236

Vous devez envoyer - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated à la vue Sélecteur avant qu'elle n'apparaisse. La documentation indique que la méthode selectedRowInComp ... donnera -1. Il est donc possible que la vue du sélecteur se trouve dans un état sans ligne sélectionnée. Il s'avère être dans cet état lors de sa création.

4
Per Arve

En temps normal, vous pouvez faire quelque chose comme ceci dans la méthode viewDidLoad;

[_picker selectRow: 1 inComponent: 0 animated: YES];

Dans mon cas, j'aimerais récupérer les données du serveur api et les afficher sur UIPickerView, puis je veux que le sélecteur sélectionne l'élément first par défaut.

UIPickerView va il ressemble à il a sélectionné le premier élément après sa création, mais lorsque vous essayez d’obtenir l’index sélectionné en utilisant selectedRowInComponent, vous obtenez NSNull. C'est parce qu'il n'a rien détecté modifié par l'utilisateur (sélectionnez 0 parmi 0).

Voici ma solution (dans viewWillAppear, après avoir récupéré les données)

[_picker selectRow:1 inComponent:0 animated:NO];
[_picker selectRow:0 inComponent:0 animated:NO];

C'est un peu sale, mais ne vous inquiétez pas, le rendu de l'interface utilisateur sous iOS est très rapide;)

1
Ryan Wu
For example: you populated your UIPickerView with array values, then you wanted 

pour sélectionner une certaine valeur de tableau dans le premier chargement de pickerView comme "Arizona". Notez que le mot "Arizona" est à l'index 2. Ce comment le faire :) Profitez du codage.

NSArray *countryArray =[NSArray arrayWithObjects:@"Alabama",@"Alaska",@"Arizona",@"Arkansas", nil];
UIPickerView *countryPicker=[[UIPickerView alloc]initWithFrame:self.view.bounds];
countryPicker.delegate=self;
countryPicker.dataSource=self;
[countryPicker selectRow:2 inComponent:0 animated:YES];
[self.view addSubview:countryPicker];
0
handiansom