Search code examples
iosobjective-cuipickerview

UIPickerView goes back to row 0 when released


I added a UIPickerView to a UITableViewCell. I am adding about 5 entries to it. Now when I try to select a value, the - (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component function is called with the correct row. But on the scrren the UIPickerView "scrolls" back to the first element and does not stick to the selected value.

Anyone had the same problem?

EventSelectCell.h

@class EventSelectCell;

@protocol EventSelectCellDelegate <NSObject>

   - (void)selectedEvent:(Event*)selectedEvent;

@end

@interface EventSelectCell : UITableViewCell <UIPickerViewDataSource, UIPickerViewDelegate>

   @property (strong, nonatomic) id <EventSelectCellDelegate> delegate;

   @property (weak, nonatomic) IBOutlet UIPickerView *selectWheel;

@end

EventSelectCell.m

#import "EventSelectCell.h"

@implementation EventSelectCell
{
    EventManager* eventManager;
    NSArray* listOfEvents;
}

- (void)awakeFromNib {
    self.selectWheel.delegate = self;
    self.selectWheel.dataSource = self;

    // get the EventManger
    eventManager = [EventManager sharedEventManager];

    listOfEvents = [eventManager getListOfEvents];

    [self.selectWheel reloadAllComponents];
}

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

    // Configure the view for the selected state
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {

    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {

    return [listOfEvents count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    Event* selectedEvent = [listOfEvents objectAtIndex:row];

    return [selectedEvent name];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    Event* selectedEvent = [listOfEvents objectAtIndex:row];

    [self.delegate selectedEvent:selectedEvent];
}

@end

the delegate

- (void)selectedEvent:(Event*)selectedEvent {
    [playersInGame removeAllObjects];

    [playersInGame addObjectsFromArray:[self.eventManager getPlayersInEvent:selectedEvent onlyActive:YES]];

    [selectedEvent setIsActive:[NSNumber numberWithInt:1]];

    activeEvent = selectedEvent;

    [self.tableView reloadData];
}

Solution

  • Okay, I found the problem. The UIPickerView is in a UITableViewCell. Whenever someone selected something with the UIPickerView I called [self.tableView reloadData], this caused the table to reload and also initialized the UIPickerView again.

    Now I am just reloading a singel section in the table.