Problème PickerView Résolu

hedihedi Membre
09:02 modifié dans Vos applications #1
Bon enfin j'ai reussii a faire ce que je veux : faire disparaitre le picker view a la selection et ne pas appeler le clavier quand j'appelle un picker

voici mon dernier.m


#import "RechercherViewController.h"


@implementation RechercherViewController

@synthesize nomTextField;
@synthesize prenomTextField;
@synthesize agence;

- (void)viewDidLoad {
   
    [super viewDidLoad];
   
    self.title = @Recherche;
   
    nomTextField.delegate = self;
    prenomTextField.delegate = self;
    agence.delegate = self;   
   
    arrayColors = [[NSArray arrayWithObjects: @Agence 1, @Agence 2, @Agence 3, @Agence 4, nil] retain];
   
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
   
    if(textField == agence)
    {
                   
        pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 264.0, 320.0, 216.0)];
        pickerView.delegate = self;
        pickerView.showsSelectionIndicator = YES;
        [pickerView selectRow:0 inComponent:0 animated:NO];
        [self.navigationController.view addSubview:pickerView];

        return NO; // POUR QUE LE CLAVIER NE SAFFICHE PAS ET NE CACHE PAS LE PICKERVIEW
    }
   
    [self.navigationController.view bringSubviewToFront:pickerView];
   
}

-(void) touchesBegan :(NSSet *) touches withEvent:(UIEvent *)event
{
    [nomTextField resignFirstResponder];
    [prenomTextField resignFirstResponder];
   
    [super touchesBegan:touches withEvent:event ];// PERMET DE FAIRE DISPARAITRE LE CLAVIER QUAND ON CLIQUE AILLEURS QUE SUR LE CHAMPS IUTEXTFIELD
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
   
    if(textField == nomTextField || textField == prenomTextField) {

        [nomTextField resignFirstResponder];
        [prenomTextField resignFirstResponder];
    }

    return YES;
}

//Retourne le nombre de colonnes dans le picker
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {   
    return 1;
}

//Retourne le nombre de lignes dans le picker
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {   
    return [arrayColors count];
}

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

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
   
    NSLog(@Selected Color: %@. Index of selected color: %i", [arrayColors objectAtIndex:row], row);
    agence.text=    [arrayColors objectAtIndex:row];

    pickerView.hidden = YES;  //PERMET DE FAIRE DISPARAITRE LE PICKER QUAND ON SELECTIONNE
}

- (IBAction) Recherche :(id)sender {
   
    UIAlertView *baseAlert = [[UIAlertView alloc]
                              initWithTitle:(@";") message:@Rentrez les bons paramètres de recherche.
                              delegate:self cancelButtonTitle:@OK
                              otherButtonTitles: nil];
    baseAlert.delegate = self;
    [baseAlert show];
    [baseAlert release];
   
}

- (void)didReceiveMemoryWarning {
   
    [super didReceiveMemoryWarning];
   
   
}

- (void)viewDidUnload {
   
}

- (void)dealloc {
    [arrayColors release];
    [nomTextField release];
    [prenomTextField release];
    [agence release];
    [super dealloc];
}

@end

Si vous avez des suggestion pour ameliorer le code je suis preneur
Sinon reste juste un petit truc qui me dérange c'est que le picker disparait vite lors de la sélection c'est à  dire dès qu'on touche la molette et on relache le picker disparait. Est qu'il y aurait possibilité de gérer le délai de disparition du picker??

Réponses

  • AliGatorAliGator Membre, Modérateur
    avril 2011 modifié #2
    Pourquoi ne pas utiliser propriété inputView de ton UITextField plutôt que de se compliquer la vie ??
    Par exemple dans ton [tt]-(void)viewDidLoad[/tt], tu crées ton picker, le configure (delegate, etc), puis tu fais juste [tt]agence.inputView = pickerView[/tt] et basta. Pas besoin de textShouldBeginEditing avec un if et tout.


    [Mode modérateur]
    Merci d'utiliser les outils des forums correctement, cela fait plusieurs fois que tu fais l'erreur
    (c'est lourd à  modérer à  force) :
    • Mettre tes questions dans la bonne catégorie/le bon forum !! Qu'est ce que ta question vient faire dans "Vos projets d'application" alors que ce n'est pas une discussion autour d'un concept de projet ou autre, pourquoi -- puisque c'est une question sur comment faire tel ou tel truc en Cocoa/ObjC -- ne pas la mettre dans la section dédiée à  toutes ces questions là , à  savoir "Utilisation des classes CocoaTouch" ?
    • Utilise les outils de formattage de tes messages (boutons juste au dessus de la zone de saisie de ton message quand tu l'écris, comme sur n'importe quel forum) en particulier pour présenter ton code source -- ou tape directement les balises [tt][co[/tt][tt]de][/tt] et [tt][/co[/tt][tt]de][/tt] pour entourer ton code source dans ton message plutôt que d'utiliser les boutons si tu préfères -- car sans ça ton code source est vraiment illisible (et qui dit message illisible dit que les bénévoles qui parcourent se forum n'auront pas envie de le lire donc d'y répondre encore moins
    • Rechercher dans les forums et lire les réponses que l'on te propose (il me semble que Buno t'avais déjà  suggéré d'utiliser inputView, à  raison puisque c'est précisément fait pour ça donc pourquoi réinventer la roue et complexifier le code et risquer d'oublier des UseCases ?
  • muqaddarmuqaddar Administrateur
    09:02 modifié #3
    Je rajoute 1 chose à  ce que dit Ali:
    - mettre des titres de sujets explicites

    Et oui c'est pas le premier de tes messages que je déplace.


  • Pourquoi ne pas utiliser propriété inputView de ton UITextField plutôt que de se compliquer la vie ??

    Par exemple dans ton [tt]-(void)viewDidLoad[/tt], tu crées ton picker, le configure (delegate, etc), puis tu fais juste [tt]agence.inputView = pickerView[/tt] et basta. Pas besoin de textShouldBeginEditing avec un if et tout.


     




     


    Bonjour, 


    Je reprends ce post.


    Je tentes d'utiliser inputView, mais sans obtenir le résultat escompté. 


    Connaissez vous un tuto qui explique cette procédure ?


    Merci par avance

  • CéroceCéroce Membre, Modérateur
    Pas de besoin de tuto, écris simplement
    textfield.input = pickerview;
    Si ça ne fonctionne pas, c'est probablement parce que le textfield ou la pickerview est nil.
  • J'ai pourtant il me semble bien codé mon pickerview.


    Le textField a été inséré dans le storyboard.


     


    Lorsque je lance le simulateur j'ai ce message dès que j'entre dans le textField :


     


    -[__NSCFConstantString count]: unrecognized selector sent to instance 0xc5040


    2014-12-14 17:53:46.349 CalcEcig[4451:117155] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString count]: unrecognized selector sent to instance 0xc5040'


    *** First throw call stack:


    (


    0   CoreFoundation                      0x0091a946 __exceptionPreprocess + 182


    1   libobjc.A.dylib                     0x005a3a97 objc_exception_throw + 44


    2   CoreFoundation                      0x009225c5 -[NSObject(NSObject) doesNotRecognizeSelector:] + 277


    3   CoreFoundation                      0x0086b3e7 ___forwarding___ + 1047


    4   CoreFoundation                      0x0086afae _CF_forwarding_prep_0 + 14


    5   CalcEcig                            0x000c24bb -[ViewControllerSweetSpot pickerView:numberOfRowsInComponent:] + 139


    6   UIKit                               0x00cba883 -[UIPickerView _delegateNumberOfRowsInComponent:] + 79


    7   UIKit                               0x00cbeb5d -[UIPickerView tableView:numberOfRowsInSection:] + 190


    8   UIKit                               0x01410aed -[UIPickerColumnView tableView:numberOfRowsInSection:] + 58


    9   UIKit                               0x00faa37f -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 2803


    10  UIKit                               0x00fb059c -[UITableViewRowData rectForFooterInSection:heightCanBeGuessed:] + 302


    11  UIKit                               0x00fb06c5 -[UITableViewRowData heightForTable] + 68


    12  UIKit                               0x00dc198c -[UITableView _updateContentSize] + 395


    13  UIKit                               0x00de44a7 -[UITableView didMoveToWindow] + 76


    14  UIKit                               0x00d535b9 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 1703


    15  UIKit                               0x00d663e1 -[UIScrollView _didMoveFromWindow:toWindow:] + 65


    16  UIKit                               0x00d5323f -[UIView(Internal) _didMoveFromWindow:toWindow:] + 813


    17  UIKit                               0x00d5323f -[UIView(Internal) _didMoveFromWindow:toWindow:] + 813


    18  UIKit                               0x00d4a517 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 154


    19  UIKit                               0x00d4a475 -[UIView(Hierarchy) _postMovedFromSuperview:] + 458


    20  UIKit                               0x00d55f0d -[UIView(Internal) _addSubview:positioned:relativeTo:] + 2018


    21  UIKit                               0x00d4886e -[UIView(Hierarchy) addSubview:] + 56


    22  UIKit                               0x00cbc5cc -[UIPickerView layoutSubviews] + 4669


    23  UIKit                               0x00cbe6cc -[UIPickerView selectedRowInComponent:] + 51


    24  UIKit                               0x00cb9c60 -[UIPickerView _updateSelectedRows] + 120


    25  UIKit                               0x00cb9db5 -[UIPickerView didMoveToWindow] + 108


    26  UIKit                               0x00d535b9 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 1703


    27  UIKit                               0x00d4a517 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 154


    28  UIKit                               0x00d4a475 -[UIView(Hierarchy) _postMovedFromSuperview:] + 458


    29  UIKit                               0x00d55f0d -[UIView(Internal) _addSubview:positioned:relativeTo:] + 2018


    30  UIKit                               0x00d4886e -[UIView(Hierarchy) addSubview:] + 56


    31  UIKit                               0x014a84cb -[UIInputWindowController changeToInputViewSet:] + 654


    32  UIKit                               0x014a91ee __43-[UIInputWindowController setInputViewSet:]_block_invoke + 103


    33  UIKit                               0x00d4f7af +[UIView(Animation) performWithoutAnimation:] + 82


    34  UIKit                               0x014a8fcc -[UIInputWindowController setInputViewSet:] + 374


    35  UIKit                               0x01243f81 __64-[UIPeripheralHost(UIKitInternal) setInputViews:animationStyle:]_block_invoke1459 + 43


    36  UIKit                               0x014a43bf -[UIInputWindowController performOperations:withAnimationStyle:] + 56


    37  UIKit                               0x01243e86 -[UIPeripheralHost(UIKitInternal) setInputViews:animationStyle:] + 1242


    38  UIKit                               0x0124405f -[UIPeripheralHost(UIKitInternal) setInputViews:animated:] + 73


    39  UIKit                               0x012440ab -[UIPeripheralHost(UIKitInternal) setInputViews:] + 68


    40  UIKit                               0x0123c298 -[UIPeripheralHost(UIKitInternal) _reloadInputViewsForResponder:] + 1803


    41  UIKit                               0x00e845a5 -[UIResponder(UIResponderInputViewAdditions) reloadInputViews] + 316


    42  UIKit                               0x00e838ec -[UIResponder becomeFirstResponder] + 562


    43  UIKit                               0x00d4a1c0 -[UIView(Hierarchy) becomeFirstResponder] + 114


    44  UIKit                               0x01515477 -[UITextField becomeFirstResponder] + 51


    45  UIKit                               0x011183ef -[UITextInteractionAssistant(UITextInteractionAssistant_Internal) setFirstResponderIfNecessary] + 200


    46  UIKit                               0x0111aa16 -[UITextInteractionAssistant(UITextInteractionAssistant_Internal) oneFingerTap:] + 2762


    47  UIKit                               0x0110e287 _UIGestureRecognizerSendActions + 327


    48  UIKit                               0x0110cb04 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 561


    49  UIKit                               0x0110eb4d -[UIGestureRecognizer _delayedUpdateGesture] + 60


    50  UIKit                               0x011124ca ___UIGestureRecognizerUpdate_block_invoke661 + 57


    51  UIKit                               0x0111238d _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 317


    52  UIKit                               0x01106296 _UIGestureRecognizerUpdate + 3720


    53  UIKit                               0x00d1f26b -[UIWindow _sendGesturesForEvent:] + 1356


    54  UIKit                               0x00d200cf -[UIWindow sendEvent:] + 769


    55  UIKit                               0x00ce5549 -[UIApplication sendEvent:] + 242


    56  UIKit                               0x00cf537e _UIApplicationHandleEventFromQueueEvent + 20690


    57  UIKit                               0x00cc9b19 _UIApplicationHandleEventQueue + 2206


    58  CoreFoundation                      0x0083e1df __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15


    59  CoreFoundation                      0x00833ced __CFRunLoopDoSources0 + 253


    60  CoreFoundation                      0x00833248 __CFRunLoopRun + 952


    61  CoreFoundation                      0x00832bcb CFRunLoopRunSpecific + 443


    62  CoreFoundation                      0x008329fb CFRunLoopRunInMode + 123


    63  GraphicsServices                    0x03c2224f GSEventRunModal + 192


    64  GraphicsServices                    0x03c2208c GSEventRun + 104


    65  UIKit                               0x00ccd8b6 UIApplicationMain + 1526


    66  CalcEcig                            0x000c2f0d main + 141


    67  libdyld.dylib                       0x02c80ac9 start + 1


    68  ???                                 0x00000001 0x0 + 1


    )


    libc++abi.dylib: terminating with uncaught exception of type NSException


     


  • AliGatorAliGator Membre, Modérateur
    Bah l'erreur et la stacktrace me paraissent suffisamment clair, non ?

    Il crash car il essaye d'appeler la méthode "count" sur une string constante. Et si tu descends un peu dans la stacktrace pour voir qui appelle la méthode pour remonter dans l'historique, tu vois que ce crash intervient dans ta méthode "[ViewControllerSweetSpot pickerView:numberOfRowsInComponent:]".

    Donc certainement que dans l'implémentation même de ta méthode "[ViewControllerSweetSpot pickerView:numberOfRowsInComponent:]" tu as fait une boulette, et appelé une méthode sur un objet NSString alors que c'est sensé être un objet NSArray ou autre.
    Ou alors c'est que ta méthode elle-même retourne un NSString alors qu'elle est sensée retourner un NSInteger (mais si c'est le cas Xcode te met un warning donc tu l'aurais vu tout de suite)

    Regarde bien ton code de "[ViewControllerSweetSpot pickerView:numberOfRowsInComponent:]", quitte à  mettre un breakpoint dedans et à  l'exécuter en pas-à -pas ligne par ligne, pour vérifier que dans chaque variable que tu manipules tu as bien l'objet attendu avec le type attendu (et donc trouver où tu as un NSString là  où tu pensais avoir un NSArray).
Connectez-vous ou Inscrivez-vous pour répondre.