2011-08-21 15 views
3

我正在創建一個需要將一年中的所有日期放入一個uitableview(每個日期都有自己的單元格)的應用程序。有沒有辦法使用nsdate來填充每個日期的每個單元格?將所有日曆日期插入到一個可用視圖中。

+0

以下方法可能與您需要爲您UITableView細胞NSDate實例幫助這個問題的答案看起來很有用:http://stackoverflow.com/questions/1472386/number-of-days-in-given-year-using-iphone-sdk – jtbandes

回答

0

如果需要顯示從1月1日到12月31日的所有日期,則需要手動創建NSDate實例。

- (NSInteger)daysInYear:(NSInteger)year { 
    if (year % 400 == 0)  return 366; 
    else if (year % 100 == 0) return 365; 
    else if (year % 4 == 0)  return 366; 
    else      return 365; 
} 


- (NSDate *)firstDayInYear:(NSInteger)year { 
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; 
    [fmt setDateFormat:@"MM/dd/yyyy"]; 
    NSDate *firstDayInYear = [fmt dateFromString:[NSString stringWithFormat:@"01/01/%d", year]]; 
    [fmt release]; 
    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]; 
} 

在你的tableView:的cellForRowAtIndexPath:方法,你就可以實例化相應的NSDate實例:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSDate *dateForCell = [self dateWithDayInterval:indexPath.row sinceDate:self.firstDayInYear]; 
    // ... rest of your method ... 
} 
+0

非常感謝。這可能會花費我一個星期的時間。一旦我終於退出與卡爾日曆 – Chris

+0

搞亂我注意到,當我把它放入分組樣式表視圖時,它停在第七個(每個部分的單元格數)並在每個部分重複自己。在分組樣式的uitableview中添加日期的最佳方式是什麼?再次感謝我所有的幫助 – Chris

+0

@pythonquick這是在uitableview所有行中重複同一天。 – 2013-06-19 09:43:53