Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically have UITableView scroll to a specific section

In my calendar app, I want my UITableView to scroll to a specific section based on which date is tapped. Current implementation is below:

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

I found a similar question that says to do it like so:

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

This gives an error stating that row is an undeclared identifier, and I want it to use the section index rather than the row anyway. How would I implement this?

like image 710
Andrew Avatar asked Jun 24 '15 05:06

Andrew


People also ask

Is UITableView scrollable?

Smooth Scrolling:- As a result, it affects the smoother scrolling experience. In UITableVIew, Scrolling will be smooth through cell reuse with the help of prepareForReuse() method.

Can UITableView scroll horizontal?

Using the horizontally scrolling cells of the UITableView enables us to develop a highly intuitive interface. It also enables the user to glance a lot of information (9 titles in the picture above).


2 Answers

Swift version of @black-sheep answer:

let sectionIndexPath = IndexPath(row: NSNotFound, section: section)
like image 104
Aleksey Shevchenko Avatar answered Oct 14 '22 21:10

Aleksey Shevchenko


Try this

[NSIndexPath indexPathForRow:NSNotFound inSection:section]
like image 31
Black Sheep Avatar answered Oct 14 '22 21:10

Black Sheep