以编程方式更改CPPickerview选择?

时间:2014-02-16 08:47:30

标签: ios uipickerview

所以我有一个开关,当它“打开”时,我希望CPPickerView切换到数组中的特定值。如果再次移动选择器视图,我希望开关移动到关闭位置。

我知道如何获取当周的当天,并尝试将选择器视图选择切换到当周的当天。

如果我离开这里问这样一个普遍的问题,请告诉我或者你是否需要更多的信息。

    //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");

    }
}

1 个答案:

答案 0 :(得分:0)

这可以通过使用CPPickerView的setSelectedItem:animated:方法以及普通的委托方法来完成。

在开启开关的todaySwitchChange:方法中,将CPPickerView设置为所需的索引:

//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");

    }
}

要在用户滚动CPPickerView时关闭开关,您需要挂钩委托方法,该方法会向您发出滚动已发生的通知:

// 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;
    }
}

希望这有帮助!