0

在我的应用程序中,我想在 UITableView 中显示一周的日期。我正在尝试下面的代码,但它在所有行中重复相同的日期。实际上我想显示的是 UITableView 中的日历日期,但星期虎钳。下面是我正在尝试的代码。希望我把我的观点说清楚,如果有任何疑问,请询问。

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

2 回答 2

2

将 indexPath.row 值添加到日期,它将在每个单元格上显示新日期。

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);

}

在 cellForRowAtIndexPath: 方法内

cell.textLable.text=[dayCollectionArray objectAtIndex:indexPath.row];

在循环中,您可以找到当天和接下来的 6 天,计算全天并添加到 NSMutableArray,而不是您可以简单地在 TableView 中显示整个星期。

于 2013-06-19T10:02:53.640 回答
0

这是我认为可以完成的新方法

    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);
于 2013-06-19T10:17:20.023 回答