UIPickerView - Loop the data

后端 未结 2 1341
时光取名叫无心
时光取名叫无心 2020-12-09 17:42

I\'m currently developing an app using Swift where I use a UIPickerView, see below for image. Currently the UIPickerView stops when the user has scrolled to the last data, b

2条回答
  •  醉梦人生
    2020-12-09 18:25

    This has already been answered here: How do you make an UIPickerView component wrap around?

    The basic idea is that you simply create a picker view with a large enough number of repeating rows that the user will likely never reach the end. In the above answer there is an issue with how the number of rows is created so I have edited that piece and provided the remaining answer below. This is objective-c so you will need to convert it to swift for your purposes...

    @implementation ViewController
    NSInteger numberItems;
    NSInteger currentValue;
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.pickerView.delegate = self;
        numberItems = 60;
        currentValue = 0;
        [self.pickerView selectRow:(currentValue + (numberItems * 50)) inComponent:0 animated:NO];
        [self.view addSubview:self.pickerView];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
    }
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
        //return NSIntegerMax; -- this does not work on 64-bit CPUs, pick an arbitrary value that the user will realistically never scroll to like this...
        return numberItems * 100;
    }
    
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
        return [NSString stringWithFormat:@"%ld", row % numberItems];
    }
    
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
        NSInteger rowValueSelected = row % numberItems;
        NSLog(@"row value selected: %ld", (long)rowValueSelected);
    }
    
    @end
    

提交回复
热议问题