Is it possible align text to both the left and right in a section heading in a tableview?

1k views Asked by At

I am trying to have some text aligned to the left of the section heading and different text to the right of the same heading.

While using toolBars I have used a flexible button to push both other buttons to the left and right and I was wondering if there was a similar thing for section headings?

A little bit more background is that I have a different section in my tableview for every piece of information entered on each different day. On the left of the section heading I want the date it was entered (Wed 20th Nov) and on the right I want how many days ago that was (20 days ago).

Here is the code I am currently using:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{    
    if (section == 0) {
        return nil;
    }
    else {
        // This gets the day the data was entered
        NSDate * date = [_sectionDates objectAtIndex:(section-1)];

        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"EEE"];
        NSString * dateDay = [formatter stringFromDate:date];
        [formatter setDateFormat:@"MMM"];
        NSString * dateMonth = [formatter stringFromDate:date];

        NSDateComponents * components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];

        NSInteger dateOfDay = [components day];

        NSTimeInterval diff = [[NSDate date] timeIntervalSinceDate:date];
        NSInteger days = diff / (60.0 * 60.0 * 24);

        NSString * dateScript;

        if (dateOfDay < 21 && dateOfDay > 4) {
            dateScript = @"th";
        }
        else if (dateOfDay % 10 == 1) {
            dateScript = @"st";
        }
        else if (dateOfDay % 10 == 2) {
            dateScript = @"nd";
        }
        else if (dateOfDay % 10 == 3) {
            dateScript = @"rd";
        }
        else {
            dateScript = @"th";
        }


        NSString * header;

        if (days < 2) {
            header = [NSString stringWithFormat:@"%@ %i%@ %@ - %@", dateDay, dateOfDay, dateScript, dateMonth, days == 0 ? bToday : bYesterday];
        }
        else {
            header = [NSString stringWithFormat:@"%@ %i%@ %@ - %i %@", dateDay, dateOfDay, dateScript, dateMonth, days, bDaysAgo];
        }

        return header;
    }
}

At the moment this outputs it like this:

|Wed 4th Dec - Today________|

I want it to be like this:

|Wed 4th Dec_________Today|

1

There are 1 answers

0
rmaddy On BEST ANSWER

You can't do it with titleForHeaderInSection. You would need to implement viewForHeaderInSection instead. Return a view with two labels - one to the left and one to the right. Of course you view would also need to replicate the default look of a standard table section header if that's what you want.