2015-06-24 51 views
0

在我的日曆應用程序中,我希望我的UITableView能夠根據哪個日期點擊滾動到特定部分。當前實現如下:如何以編程方式將UITableView滾動到特定部分

- (void)calendarDidDateSelected:(JTCalendar *)calendar date:(NSDate *)date 
{ 
    // Format NSDate so it can be compared to date selected 
    static NSDateFormatter *dateFormatter = nil; 
    if(!dateFormatter){ 
     dateFormatter = [NSDateFormatter new]; 
     dateFormatter.dateFormat = @"yyyy-MM-dd"; // Read the documentation for dateFormat 
    } 

    // Set formatted dates 
    NSDate *juneSixteenth = [dateFormatter dateFromString:@"2015-06-16"]; 
    NSDate *juneSeventeenth = [dateFormatter dateFromString:@"2015-06-17"]; 

    // Set date selected, so agendaTable knows which event to show 
    if([juneSixteenth compare:date] == NSOrderedSame){ 
     NSLog(@"You picked June 16th"); 
     self.datePicked = [NSNumber numberWithInt:16]; 
    } 
    else if([juneSeventeenth compare:date] == NSOrderedSame){ 
     NSLog(@"You picked June 17th"); 
     self.datePicked = [NSNumber numberWithInt:17]; 
    } 
    else { 
     _datePicked = nil; 
     NSLog(@"Date: %@", date); 
    } 
    [self.agendaTable reloadData]; 
} 

我發現了一個類似的question,說這樣做像這樣:

 if([juneSixteenth compare:date] == NSOrderedSame){ 
      NSLog(@"You picked June 16th"); 
      self.datePicked = [NSNumber numberWithInt:16]; 

      //"row" below is row selected in the picker view 
      NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:row]; 

      [self.agendaTable scrollToRowAtIndexPath:ip 
          atScrollPosition:UITableViewScrollPositionNone 
            animated:YES]; 
     } 

這給出了一個錯誤,指出row是一個未聲明的標識符,我希望它用無論如何,該部分索引而不是行。我將如何實現這一點?

回答

8

試試這個[NSIndexPath indexPathForRow:NSNotFound inSection:section]

+1

工程於iOS10/11大。高雅的解決方 –

0

你必須找到/計算h和使用要滾動

NSInteger row = ??;//you have to find/calculate which row you want to show 
NSInteger section = ??;//you have to find/calculate which row of the sections you want to show 
NSIndexPath *ip = [NSIndexPath indexPathForRow:row inSection:section]; 

[self.agendaTable scrollToRowAtIndexPath:ip 
         atScrollPosition:UITableViewScrollPositionNone 
           animated:YES]; 
4

sectionrow是必須是int值和變量定義這個變量在.m類中的任何地方,你想要在特定位置上滾動。

您可以在特定部分滾動的UITableView,你也可以使用下面的代碼滾動到節的特定索引單元:

SIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
[MytblView scrollToRowAtIndexPath:indexPath 
        atScrollPosition:UITableViewScrollPositionTop 
          animated:YES]; 
4

雨燕3.0

DispatchQueue.main.async { 
    let indexPath = IndexPath(item: 'item', section: 'section') 
    self.tableView.scrollToRow(at: indexPath, at: .top, animated: true) 
} 
相關問題