Как сделать бесконечный UIPickerView?

У меня есть вид выбора, где пользователь вводит время. Когда они прокручиваются до 23-го часа, я хочу, чтобы нулевой час отображался как следующий элемент, а последовательность запускалась заново. Как я могу этого добиться?

Вот мой текущий источник данных представления выбора:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3; 
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
  NSArray *sectionContents = [[self dataForDatapickerRows] objectAtIndex:component];    
  NSInteger rows = [sectionContents count];     
  NSLog(@"component %d rows is: %d",component,rows);    
  return rows;  
}
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component {
  self.dataPickerInstance.backgroundColor=[UIColor whiteColor];       
  return ([[[self dataForDatapickerRows ]objectAtIndex:component] objectAtIndex:row]);
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if(component==0)
    {
      [self setHou:(NSInteger*)[[[self dataForDatapickerRows ]objectAtIndex:component] objectAtIndex:row]];
    }
    else if(component==1)
    {
      [self setMinut:(NSInteger*)[[[self dataForDatapickerRows ]objectAtIndex:component] objectAtIndex:row]];
    }
    else if(component==2)
    {
      [self setSecon:(NSInteger*)[[[self dataForDatapickerRows ]objectAtIndex:component] objectAtIndex:row]];
    }

    NSLog(@"%@",[[[self dataForDatapickerRows ]objectAtIndex:component] objectAtIndex:row]); 
}


- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* tView = (UILabel*)view;

    if (!tView){
        tView = [[UILabel alloc] init];
        [tView setFrame:CGRectMake(0, 0, 90,60)];
        tView.self.textColor=[UIColor whiteColor];
        tView.minimumFontSize = 80;
        tView.textAlignment=UITextAlignmentCenter;
        tView.adjustsFontSizeToFitWidth = YES;
        tView.autoresizesSubviews=YES;
        tView.font = [UIFont boldSystemFontOfSize:40];
        tView.backgroundColor = [UIColor blackColor];


        //tView.highlightedTextColor=[UIColor greenColor];
        // factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, factLabel.frame.size.width, lLabelSIze.height);
        //
        // Setup label properties - frame, font, colors etc
    }   // Fill the label text here
     tView.text=[[[self dataForDatapickerRows ]objectAtIndex:component] objectAtIndex:row];   

   return tView; 
}

введите здесь описание изображения


person Arun    schedule 09.02.2012    source источник


Ответы (2)


У меня есть пользовательское средство выбора времени (UIPickerView), для которого делегат выглядит так:

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 4; // it's with am/pm in my case
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    /// 18000 is divisible with 12, 24 (for the hour) and 60 (for the minutes and seconds)
    /// it can still get to the end.. but will need a lot of scrolling
    /// I set the initial value between 9000 and 9060
    if (component==0) { // hour
        return 18000;
    }
    if (component==3) { // am/pm
        return [_datasource count];
    }
      // seconds and minutes - could use 45000 so it repeats the same number of time as the hours
    return 18000;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component==3) { // am/pm
        return [_datasource objectAtIndex:row];
    }
    if (component==0) { // hour
        return [NSString stringWithFormat:@"%d", row%12];
    }
    return [NSString stringWithFormat:@"%02d", row%60];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component==3) { // am/pm
        if (row==0&&_h>11) {
            _h-=12;
        }
        if (row==1&_h<12) {
            _h+=12;
        }
    }
    else if(component==0){
        _h=row%12;
        if ([self selectedRowInComponent:3]==1) { // handle am/pm
            _h+=12;
        }
    }
    else if(component==1){
        _m=row%60;
    }
    else if(component==2){
        _s=row%60;
    }
}
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    // set the size for components
    if (component<3) {
        return 50;
    }
    return 70;
}
person alex-i    schedule 09.02.2012
comment
привет друг, во-первых, я должен сказать спасибо. В вашем коде мне нужно увеличить количество строк до 18000, но мне нужно только 24 для часа и 60 для секунды и минуты, тогда что мне нужно сделать. У вас есть идеи? Поделись, пожалуйста - person Arun; 09.02.2012
comment
Во-первых, удалите последний компонент из всех методов (am/pm). Затем вам нужно будет изменить pickerView:titleForRow:forComponent: для ваших нужд (например: чтобы час принимал значения от 0 до 23, используйте [NSString stringWithFormat:@"%d", row%24], чтобы принимать значения от 1 до 24, используйте [NSString stringWithFormat:@"%d", row%24+1]). Секунды и минуты уже принимают значения только от 0 до 59. Проверьте ссылку из поста user792677, она может объяснить лучше (она использует ту же идею и прокручивается обратно к середине после выбора нового значения). - person alex-i; 09.02.2012
comment
о.. вам также нужно изменить pickerView:didSelectRow:inComponent:, чтобы вернуть те же значения (удалите первое, если - am/pm - в component==0 _h (час) будет строка% 24 (или строка% 24+1, зависит от того, как вы ее используете в методе titleForRow:). - person alex-i; 09.02.2012
comment
Привет, друг, спасибо за эту идею, и могу ли я узнать количество строк для этой вышеприведенной логики .... это 24,60 и 60 больше, чем это ... Требуется всего 24,60,60 друг в пределах это возможно ... - person Arun; 09.02.2012
comment
скажем, что минутная составляющая равна 9832, тогда минута будет 9832%60 (== 52, % остаток для деления 9832 на 60). Следовательно, минута будет 52. Если прокрутить до 9833, минута будет 53. При прокрутке до 9840 минута будет 9840%60 (== 0), поэтому после 59 снова будет отображаться 0. Я надеюсь, что это ясно. - person alex-i; 09.02.2012

Вот один из возможных способов сделать то, что вы хотите, выглядит не очень красиво, но должен работать: Архив блога Pauldy's House of Geek The Abusive PickerView

Вы в основном создаете много, много, много повторяющихся элементов, чтобы имитировать цикл.

person A-Live    schedule 09.02.2012