如何以编程方式将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]; } 

我发现了一个类似的问题 ,说是这样做的:

  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是未声明的标识符,我希望它仍然使用节索引而不是行。 我该如何实现?

试试这个[NSIndexPath indexPathForRow:NSNotFound inSection:section]

Swift 3.0

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

Row必须是int值,并且该变量在.h中定义,并在.m类中的任何位置使用此变量,您要在特定位置滚动。

您可以在特定部分滚动UITableView,也可以使用以下代码滚动到部分的特定索引单元格:

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

如果您的部分没有单元格,例如它只有页眉或页脚,您可以使用以下选项之一:

 let sectionRect = yourTable.rect(forSection: sectionNumber) yourTable.setContentOffset(CGPoint(x: sectionRect.origin.x, y: sectionRect.origin.y), animated: true) 

要么

 let sectionRect = yourTable.rect(forSection: sectionNumber) yourTable.scrollRectToVisible(sectionRect, animated: false) 

您必须查找/计算要滚动的sectionrow

 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];