在我的日历应用中,我希望我的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
是未声明的标识符,我希望它仍然使用节索引而不是行。我该如何实现呢?
答案 0 :(得分:36)
试试这个[NSIndexPath indexPathForRow:NSNotFound inSection:section]
答案 1 :(得分:14)
Swift 3.0
DispatchQueue.main.async {
let indexPath = IndexPath(item: 'item', section: 'section')
self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
答案 2 :(得分:6)
行必须是int值,并且该变量在.h中定义,并在.m类中的任何位置使用此变量,以便在特定位置滚动。
您可以在特定部分滚动UITableView,也可以使用以下代码滚动到部分的特定索引单元格:
SIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[MytblView scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
答案 3 :(得分:3)
如果您的部分没有单元格,例如它只有页眉或页脚,您可以使用以下选项之一:
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)
答案 4 :(得分:3)
@ black-sheep答案的快速版本:
let sectionIndexPath = IndexPath(row: NSNotFound, section: section)
答案 5 :(得分:1)
您必须查找/计算要滚动的section
和row
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];