![](/img/trans.png)
[英]How to scroll to specific section in UITableView (or ListView of android) and update on bar?
[英]How to programmatically have UITableView scroll to a specific section
在我的日历应用程序中,我希望我的 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]
斯威夫特 3.0
DispatchQueue.main.async {
let indexPath = IndexPath(item: 'item', section: 'section')
self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
@black-sheep 答案的 Swift 版本:
let sectionIndexPath = IndexPath(row: NSNotFound, section: section)
当您的部分没有单元格时,例如它只有页眉或页脚,您可以使用以下选项之一:
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)
行必须是 int 值,该变量定义在 .h 中,并在 .m 类中的任何地方使用此变量,您要在特定位置滚动。
您可以在特定部分滚动 UITableView,也可以使用以下代码滚动到部分的特定索引单元格:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[MytblView scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
您必须找到/计算要滚动的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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.