Добавить / вычесть ячейки в UITableView - PullRequest
0 голосов
/ 11 ноября 2011

В моем приложении UITableView с 3 ячейками.Если пользователь выбирает одну из двух верхних ячеек, он может изменить значение с помощью UIDatePicker, например, «11 ноября 2011 года».

Есть ли способ вычесть даты из первой ячейки во вторую?

Как пользователь вводит «11 ноября 2011 года» в первую ячейку, а во второй ячейке вводит «11 ноября 2012 года», как я могу получить в 3-й ячейке сообщение «1» или «1 год "?

Мой код -

.h

IBOutlet UIDatePicker *datePicker;
    UITableView *products;
    NSMutableArray *productsInfo, *extras;
    NSDateFormatter *dateFormatter;
}

@property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
@property (nonatomic,retain) IBOutlet UITableView *products;
@property (nonatomic,retain) NSDateFormatter *dateFormatter;;
-(IBAction)DateChanged:(id)sender;

.m -

@implementation PushedViewController

@synthesize datePicker;
@synthesize products,dateFormatter;

-(IBAction)DateChanged:(id)sender{
    NSIndexPath *indexPath = [self.products indexPathForSelectedRow];
    UITableViewCell *cell = [self.products cellForRowAtIndexPath:indexPath];
    cell.detailTextLabel.text = [self.dateFormatter stringFromDate:self.datePicker.date];
}

- (void)viewDidLoad
{

    self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [self.dateFormatter setDateStyle:NSDateFormatterLongStyle];
    productsInfo = [[NSMutableArray alloc]init];
    extras = [[NSMutableArray alloc]init];
    [extras addObject:@"Time Left"];
    [productsInfo addObject:@"Date Bought"];
    [productsInfo addObject:@"Date Ending"];

    //product.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"MakeText"];
    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section==0){
        return [productsInfo count];
    }
    else{
        return [extras count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    if (indexPath.section==0){
        cell.textLabel.text = [productsInfo objectAtIndex:indexPath.row];
        cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[NSDate date]];
    }
    else {
        cell.textLabel.text = @"Time Left";
        cell.detailTextLabel.text = @"8";
    }


    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *targetCell = [tableView cellForRowAtIndexPath:indexPath];

}

@end

Ответы [ 2 ]

0 голосов
/ 11 ноября 2011

Для этого вам нужно будет сохранить каждую из этих двух дат, выбранных в ячейках, в переменной экземпляра для ссылки в третьей ячейке.После того, как в третьей ячейке есть обе даты, необходимые для вычисления, все становится немного сложнее.Используя два NSDate s, вы хотите вывести пользователю временной интервал в человеческих словах.Для этого нет никаких фабричных методов, но мой друг создал полезный класс TTTTimeIntervalFormatter, который будет делать именно это.

Вы можете использовать его следующим образом:

NSDate *dateFromFirstDatePicker = [datePicker1 date];
NSDate *dateFromSecondDatePicker = [datePicker2 date];
TTTTimeIntervalFormatter *timeIntervalFormatter = [[TTTTimeIntervalFormatter alloc] init];

NSString *timeInterval = [timeIntervalFormatter stringForTimeInterval:[dateFromFirstDatePicker timeIntervalSinceDate:dateFromSecondDatePicker]];

//other examples
[timeIntervalFormatter stringForTimeInterval:0]; // "just now"
[timeIntervalFormatter stringForTimeInterval:100]; // "1 minute ago"
[timeIntervalFormatter stringForTimeInterval:8000]; // "2 hours ago"

[timeIntervalFormatter release];

Затем вы можете обновить третью ячейку, используя стандартный UITableViewDataSource метод cellForRowAtIndexPath: для обновления содержимого ячейки.

0 голосов
/ 11 ноября 2011

Ну, вы можете сделать это в:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if([indexPath row] == 1){
      // Get the date from the cell:
      UITableViewCell *cell=[table cellForRowAtIndexPath:indexPath];
      // Take care of the date
      // (...)
      // Give it to the other cells:
      UITableViewCell *cell=[table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; // this is a reference to the second cell in the table (I assume you have 3: 0,1,2)
    }
}       

И затем делать то, что вы хотите со своей клеткой.

...