Search code examples
iosuipickerview

Change CPPickerview selection programmatically?


So i have a switch and when it is "on" i would like the CPPickerView to switch to a particular value in an array. As well if the pickerview is moved again i would like the switch to move to the off position.

I know how to get the current day of the week and am trying to switch the pickerview selection to the current day of the week.

If i am way off base here asking such a generalised question just let me know or if you need any more information.

    //CPPicker
    self.daysOfWeekData = [[NSArray alloc] initWithObjects:@"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", @"Sunday", nil];
    self.dayPickerView.allowSlowDeceleration = YES;
    [self.dayPickerView reloadData];
#pragma mark - Horizontal pickerview

//DataSource
-(NSInteger)numberOfItemsInPickerView:(CPPickerView *)pickerView {
    return 7;
}

-(NSString *)pickerView:(CPPickerView *)pickerView titleForItem:(NSInteger)item {
    return daysOfWeekData[item];
}

//Delegate
-(void)pickerView:(CPPickerView *)pickerView didSelectItem:(NSInteger)item {
    self.dayLabel.text = [NSString stringWithFormat:@"%@", daysOfWeekData[item]];
}

//Today's day date
- (IBAction)todaySwitchChange:(id)sender {

    if (todaySwitch.on) {

         NSLog(@"It is on");

    } else {

        NSLog(@"It is off");

    }
}

Solution

  • This can be done by using CPPickerView's setSelectedItem:animated: method, along with the normal delegate methods.

    In your todaySwitchChange: method when the switch is turned on, set the CPPickerView to your desired index:

    //Today's day date
    - (IBAction)todaySwitchChange:(id)sender {
    
        if (todaySwitch.on) {
            NSLog(@"It is on");
    
            // This will cause the CPPickerView to select the item you choose
            NSUInteger itemToSelect = someValue; //whatever logic you need to select the right index
            [self.dayPickerView setSelectedItem:itemToSelect animated:YES]; // Or disable animation if desired
    
        } else {
    
            NSLog(@"It is off");
    
        }
    }
    

    To toggle the switch off when the user scrolls on the CPPickerView, you'll need to hook into the delegate method which gives you notification that scrolling has occurred:

    // Implement the following delegate method
    - (void)pickerViewWillBeginChangingItem:(CPPickerView *)pickerView {
        // Picker is going to change due to user scrolling, so turn the switch off
        if (todaySwitch.on) {
            todaySwitch.on = NO;
        }
    }
    

    Hope this helps!