mardi 23 juin 2015

How to reference only the first object in indexPathsForVisibleRows

What I'm trying to do is detect which sections of a UITableView are visible, and then change the date of a calendar based on which are visible.

The issue is that there are typically multiple sections viewable at the same time, and I only want to change the date based on the first section index that appears in visibleRowIndexes, not all of them.

Here's my current implementation (Note: I run this function in cellForRowAtIndexPath):

-(BOOL)whatSectionsAreVisible {

    NSArray *visibleRowIndexes = [self.agendaTable indexPathsForVisibleRows];

    for (NSIndexPath *index in visibleRowIndexes) {
        NSNumber *daySection = @(index.section);

        static NSDateFormatter *dateFormatter = nil;
            dateFormatter = [NSDateFormatter new];
            dateFormatter.dateFormat = @"yyyy-MM-dd"; // Read the documentation for dateFormat

        // Here is where I will map every index.section to an NSDate
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        [comps setDay:daySection.intValue]; // <<== Extract int from daySection
        [comps setMonth:6];
        [comps setYear:2015];
        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDate *date = [gregorian dateFromComponents:comps];

        // Update the day selected according to visible section
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kJTCalendarDaySelected" object:date];

        // Store currentDateSelected
        [self.calendar setCurrentDateSelected:date];

        NSLog(@"The visible section has an index of: %ld", (long)index.section);

        if (index.section == 0) {
            NSLog(@"index.row is indeed 0");
            return YES;
    return NO;

I tried doing something like NSNumber *daySection = @(index[0].section); instead of NSNumber *daySection = @(index.section);, but that doesn't seem to work.

See more ..

Aucun commentaire:

Enregistrer un commentaire