在我的应用程序中,我想在UITableView中显示本周的日期。我正在尝试下面的代码,但它在所有行中重复相同的日期。实际上我想要显示的是UITableView中的日历日期,但周vise.Below是我正在尝试的代码。希望我明确指出,如果有任何疑问,请问。
-(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];
}
答案 0 :(得分: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:method
中cell.textLable.text = [dayCollectionArray objectAtIndex:indexPath.row];
在循环内你可以找到taday的一天和接下来的6天, 计算全天并添加到NSMutableArray,而不是只在TableView中显示整周。
答案 1 :(得分: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);