2016-01-07 2 views
0

У меня есть tableView, и в одной из строк у меня есть горизонтальный scrollView и некоторые изображения (изображения находятся в другом представлении строки). В горизонтальном scrollView я добавил несколько кнопок (10 кнопок). когда пользователь нажимает на любую кнопку из scrollView, я вызываю reloadData. Потому что я звоню reloadData, поэтому горизонтальный scrollView снова загружает новые данные. Теперь я хочу, чтобы пользователь прокручивался до конца и нажал последнюю кнопку из scrollView, пользователь должен уметь видеть, что выбранная кнопка не первая. Я не знаю, как я могу использовать scrollRectToVisible:animated, чтобы это произошло.Как использовать scrollRectToVisible: анимированный?

вот мой код для scrollView и кнопки добавления на нем.

-(void)addColorFiltersOnView:(UIView *)colorView{  
    if (_colorFilterView) { 
     [_colorFilterView removeFromSuperview]; 
    } 

    self.colorFilterView = [[UIScrollView alloc] initWithFrame:colorView.bounds]; 
    [_colorFilterView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight]; 
    [_colorFilterView setBackgroundColor:samergb(238)]; 
    [_colorFilterView setShowsHorizontalScrollIndicator:NO]; 

    int addedCount = 0; 
    int i=0; 

    CGFloat x = 10, y = 5; 

    if ([_colorFilters count] < 1) { 
     return; 
    } 

    for (i=0; i<[_colorFilters count] - 1; i++) { 

     id item = [_colorFilters objectAtIndex:i]; 

     if ([item isKindOfClass:[NSString class]]){ 

      if ([self.prodVIPDictionary.PDcolor isEqualToString:(NSString*)item] && i != 0) { 
       continue; 
      } 

      NSInteger itemsCount = [[_colorFilters objectAtIndex:i+1] integerValue]; 

      if (itemsCount <= 0) { 
       break; 
      } 

      TTTAttributedLabel *itemLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero]; 
      [itemLabel setNumberOfLines:1]; 
      [itemLabel setTextAlignment:NSTextAlignmentCenter]; 
      [itemLabel setFont:[UIFont systemFontOfSize:14]]; 

      if ([_selectedColor isEqualToString:(NSString*)item]) 
       [itemLabel setTextColor:[UIColor whiteColor]]; 

      [itemLabel setText:[(NSString*)item capitalizedString]]; 
      [itemLabel setBackgroundColor:samergb(255)]; 
      itemLabel.layer.borderWidth = 1; 
      itemLabel.layer.masksToBounds = YES; 
      itemLabel.layer.cornerRadius = 10; 
      itemLabel.layer.borderColor = samergb(210).CGColor; 
      [itemLabel sizeToFit]; 
      [_colorFilterView addSubview:itemLabel]; 

      CGRect itemFrame = itemLabel.frame; 
      itemFrame.size.width += 20; 
      [itemLabel setFrame:itemFrame]; 

      UIButton *optionBtn = [[UIButton alloc] initWithFrame:CGRectMake(x, y, itemLabel.frame.size.width + 6, 26)]; 
      [optionBtn setTag:[_colorFilters indexOfObject:item]]; 
      [optionBtn addTarget:self action:@selector(optionColorClicked:) forControlEvents:UIControlEventTouchUpInside]; 

      [_colorFilterView addSubview:optionBtn]; 

      [itemLabel setFrame:optionBtn.frame]; 

      if ([_selectedColor isEqualToString:(NSString*)item]) { 
       [optionBtn setEnabled:NO]; 
       [itemLabel setBackgroundColor:[LRUtils lrGreenColor]]; 
      } 

      addedCount ++; 

      x += optionBtn.frame.size.width+5; 

      if (addedCount >= 20) { 
       break; 
      } 

     }else{ 
      continue; 
     } 
    } 

    [_colorFilterView setContentSize:CGSizeMake((x + 10),colorView.frame.size.height)]; 
    [colorView addSubview:_colorFilterView]; 
} 
+0

Это не очень понятно. Если пользователь прокручивает и нажимает последнюю кнопку, что на самом деле происходит по сравнению с тем, что вы хотите? Почему-то прокрутка возвращается к началу? Возможно, вам следует обновить свой вопрос с помощью метода 'optionColorClicked:'. – rmaddy

+0

@rmaddy Я только что обновил свой вопрос. – Zac24

ответ

0

Вместо вызова reloadData, вы могли бы назвать этот метод на Table View:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

Вам нужно будет создать NSArray, содержащий все IndexPaths в таблице View кроме для строки со списком прокрутки и кнопками. Таким образом, просмотр прокрутки не будет сброшен.

+0

Это единственный вариант, который я подумал, но не пробовал, потому что данные scrollView и Image находятся в одной и той же ячейке, поэтому, даже если я использую reloadRowsAtIndexPath, ScrollView будет сброшен. Я думаю, что нет другого пути, кроме создания scrollView в отдельной ячейке. – Zac24

Смежные вопросы