![](/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.