UIPickerView实现循环滚动

来源:互联网 发布:淘宝美工教程视频 编辑:程序博客网 时间:2024/06/04 19:11

为了UIPickerView实现循环滚动,需要实现UIPickerView的代理以及数据源方法,实现pickerViewLoaded方法,并在didSelectRow方法中调用[selfpickerViewLoaded:component];

需要注意以下两点:

1.numberOfRowsInComponent方法中返回值最好与pickerViewLoaded方法中max保持一致

2.按以下方法实现后,pickerView初始位置位于(0,0),直接向下滑动即可实现无限循环滚动,但直接向上滑动时会有一次加载效果,虽然只会出现一次,但还是影响整体效果,可在viewDidLoad中调用[datePickerselectRow:(16384 /2 -8inComponent:0animated:YES]; [datePickerselectRow:(16384 /2)  inComponent:1animated:YES];让pickerView初始选择中间行来解决这个问题


下面是我在某个项目中的PickerView代理以及数据源方法,仅供参考,如有问题,欢迎指正。

#pragma mark - PickerViewDelegate- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {    return self.view.frame.size.width / 2;}- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {    return 30;}- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView      {    return 2;}- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component     {    return 16384;}- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component    {    NSArray *strArray = component ? @[@"00", @"15", @"30", @"45"] : @[@"00", @"01", @"02", @"03", @"04", @"05", @"06", @"07", @"08", @"09", @"10", @"11", @"12", @"13", @"14", @"15", @"16", @"17", @"18", @"19", @"20", @"21", @"22", @"23"];    NSString *titleStr = strArray[component ? (int)(row%4) : (int)(row%24)];    NSAttributedString *attributedTitleStr= [[NSAttributedString alloc] initWithString:titleStr attributes:@{NSAttachmentAttributeName: [UIFont systemFontOfSize:30], NSForegroundColorAttributeName: [UIColor whiteColor]}];    return attributedTitleStr;}- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component  {    [self pickerViewLoaded:component];    NSArray *strArray = component ? @[@"00", @"15", @"30", @"45"] : @[@"00", @"01", @"02", @"03", @"04", @"05", @"06", @"07", @"08", @"09", @"10", @"11", @"12", @"13", @"14", @"15", @"16", @"17", @"18", @"19", @"20", @"21", @"22", @"23"];    SelectionData *tempData = self.selectionDataArray[selectIndex];    if (component) {        tempData.selectMin = strArray[row % 4];    }   else    {        tempData.selectHour = strArray[row % 24];    }    [self.selectionDataArray replaceObjectAtIndex:selectIndex withObject:tempData];}-(void)pickerViewLoaded: (NSInteger)component {    NSUInteger max = 16384;    NSUInteger base10 = (max / 2) - (max / 2) % (component ? 4 : 24);    [dateBGView.datePicker selectRow:[dateBGView.datePicker selectedRowInComponent:component] % (component ? 4 : 24) + base10 inComponent:component animated:NO];}

0 1
原创粉丝点击