Reputation:
In my app i want to show the week's dates in UITableView. I am trying the below code but it is repeating the same date in all rows. Actually what i want to show is the calendar dates in UITableView but week vise.Below is code i am trying. Hope i made my point clear, if any doubt please ask.
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell;
if(tableView == self.mWeekTable)
{
static NSString *cellIdentifier = @"Cell";
cell = [self.mLocationTable dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
NSDate *dateForCell = [self dateWithDayInterval:indexPath.row sinceDate:firstDayInYear];
// NSDate *date = [NSDate date];
//NSDate *dateForCell = [self nextDayFromDate:date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-EEEE"];
NSString *stringFromDate = [formatter stringFromDate:dateForCell];
cell.textLabel.text = stringFromDate;
}
}
- (NSDate *)firstDayInYear:(NSInteger)year {
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"MM/dd/yyyy"];
firstDayInYear = [fmt dateFromString:[NSString stringWithFormat:@"01/01/%d", year]];
return firstDayInYear;
}
- (NSDate *)dateWithDayInterval:(NSInteger)dayInterval sinceDate:(NSDate *)referenceDate {
static NSInteger SECONDS_PER_DAY = 60 * 60 * 24;
return [NSDate dateWithTimeInterval:dayInterval * SECONDS_PER_DAY sinceDate:referenceDate];
}
Upvotes: 0
Views: 528
Reputation: 861
Add the indexPath.row value to date, it will display new date on each cell.
NSMutableArray *dayCollectionArray=[[NSMutableArray alloc]init];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd"];
for (int i = 0; i<7; i++) {
NSDate *nextDay = [NSDate dateWithTimeInterval:(i*24*60*60) sinceDate:[NSDate date]];
NSString *day=[dateFormatter stringFromDate:nextDay];
[dayCollectionArray addObject:day];
NSLog(@"day=%d == =%@",i,day);
}
inside cellForRowAtIndexPath: method
cell.textLable.text=[dayCollectionArray objectAtIndex:indexPath.row];
inside the loop you can find taday's day and next 6 days, calculate all day and add to NSMutableArray than you can simply display whole week in a TableView.
Upvotes: 2
Reputation: 1028
This is new way that i think it could be accomplished
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:16];
[comps setMonth:6];
[comps setYear:2013];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE MM"];
NSString *day = [dateFormatter stringFromDate:date];
[comps release];
[gregorian release];
NSLog(@"Weekday : %@", day);
Upvotes: 0