2013-04-18 2 views
0

Я хотел бы знать, есть ли у меня подходящий, название каждого элемента таблицы - это дата и время. Могу ли я узнать, как закодировать, если я хочу, чтобы таблица автоматически прокручивалась до ячейки с определенной датой, например. Сегодняшняя дата? Что мне следует кодировать в методе viewDidLoad?Прокрутите вниз uitableview до определенной даты

Вот мой код для таблицы,

@interface PictureListMainTable : UITableViewController{ 
    IBOutlet UIButton*scroll; 

} 

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext; 
@property (strong, nonatomic) NSMutableArray *pictureListData; 
@property (strong, nonatomic) IBOutlet UIButton*scroll; 

- (void)readDataForTable; 
-(IBAction)scrolldown:(id)sender; 
@end 



@synthesize managedObjectContext, pictureListData; 
@synthesize scroll; 



// When the view reappears, read new data for table 
- (void)viewWillAppear:(BOOL)animated 
{ 
    // Repopulate the array with new table data 
    [self readDataForTable]; 
} 

// Grab data for table - this will be used whenever the list appears or reappears after an add/edit 
- (void)readDataForTable 
{ 
    // Grab the data 
    pictureListData = [CoreDataHelper getObjectsForEntity:@"Pictures" withSortKey:@"title" andSortAscending:YES andContext:managedObjectContext]; 

    // Force table refresh 
    [self.tableView reloadData]; 
} 

#pragma mark - Actions 

// Button to log out of app (dismiss the modal view!) 
- (IBAction)logoutButtonPressed:(id)sender 
{ 
    [self dismissModalViewControllerAnimated:YES]; 
} 

#pragma mark - Segue methods 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    // Get a reference to our detail view 
    PictureListDetail *pld = (PictureListDetail *)[segue destinationViewController]; 

    // Pass the managed object context to the destination view controller 
    pld.managedObjectContext = managedObjectContext; 

    // If we are editing a picture we need to pass some stuff, so check the segue title first 
    if ([[segue identifier] isEqualToString:@"EditPicture"]) 
    { 
     // Get the row we selected to view 
     NSInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row]; 

     // Pass the picture object from the table that we want to view 
     pld.currentPicture = [pictureListData objectAtIndex:selectedIndex]; 
    } 
} 

#pragma mark - Table view data source 

// Return the number of sections in the table 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

// Return the number of rows in the section (the amount of items in our array) 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [pictureListData count]; 
} 

// Create/reuse a table cell and configure it for display 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

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

    // Get the core data object we need to use to populate this table cell 
    Pictures *currentCell = [pictureListData objectAtIndex:indexPath.row]; 

    // Fill in the cell contents 
    cell.textLabel.text = [currentCell title]; 
    cell.detailTextLabel.text = [currentCell desc]; 

    // If a picture exists then use it 
    if ([currentCell smallPicture]) 
    { 
     cell.imageView.contentMode = UIViewContentModeScaleAspectFit; 
     cell.imageView.image = [UIImage imageWithData:[currentCell smallPicture]]; 
    } 

    return cell; 
} 

// Swipe to delete has been used. Remove the table item 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    { 
     // Get a reference to the table item in our data array 
     Pictures *itemToDelete = [self.pictureListData objectAtIndex:indexPath.row]; 

     // Delete the item in Core Data 
     [self.managedObjectContext deleteObject:itemToDelete]; 

     // Remove the item from our array 
     [pictureListData removeObjectAtIndex:indexPath.row]; 

     // Commit the deletion in core data 
     NSError *error; 
     if (![self.managedObjectContext save:&error]) 
      NSLog(@"Failed to delete picture item with error: %@", [error domain]); 

     // Delete the row from the data source 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
} 

@end 

Благодаря

+0

Будет ли несколько раз даты на один день в вашем DataSource? – Anupdas

+0

Нет. На каждую ячейку в день будет только одна информация NSDate. Спасибо – Clarence

ответ

2

Поскольку вы имеете дело с датами, это лучше создать массив дат и найти текущую дату, используя dateC omponents.

В этом фрагменте датируется массив из NSDate экземпляров.

NSCalendar *cal = [NSCalendar currentCalendar]; 

NSDate *today = [NSDate date]; 
[self.dates enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    NSDate *date = (NSDate *)obj; 
    NSDateComponents *components = [cal components:NSDayCalendarUnit 
              fromDate:date 
              toDate:today 
              options:0]; 
    if ([components day]==0) { 
     *stop = TRUE; 
     NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0]; 
     [self.tableView scrollToRowAtIndexPath:indexPath 
           atScrollPosition:UITableViewScrollPositionTop 
             animated:YES]; 
    } 
}]; 

EDIT:

- (void)viewWillAppear:(BOOL)animated 
{ 
    // Repopulate the array with new table data 
    [self readDataForTable]; 

    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
    [dateFormatter setDateFormat:@"dd.MMMM - EEEE"]; 
    NSDate *today = [NSDate date]; 
    [pictureListData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
     Pictures *picture = (Pictures *)obj; 
     NSDate *date = [dateFormatter dateFromString:picture.title]; 
     NSDateComponents *components = [cal components:NSDayCalendarUnit 
               fromDate:date 
               toDate:today 
               options:0]; 
     if ([components day]==0) { 
      *stop = TRUE; 
      NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0]; 
      [self.tableView scrollToRowAtIndexPath:indexPath 
            atScrollPosition:UITableViewScrollPositionTop 
              animated:YES]; 
     } 
    }]; 
} 
+0

Я думаю, что ваш метод отличный, но я не могу понять, как его поместить в мой код. Можете ли вы научить меня, как настроить в соответствии с моим кодом? Спасибо – Clarence

+0

@Clarence Можете ли вы показать мне датуФормат «title» в картинках? – Anupdas

+0

Этот код относится к подробному представлению таблицы. NSDate * currdate = [datepicker date]; NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat: @ "dd.MMMM - EEEE"]; NSString * timeStr = [dateFormatter stringFromDate: currdate]; titleField.text = [NSString stringWithFormat: @ "% @", timeStr]; – Clarence

0

Вы должны рассчитать indexpath для specific date. И использовать этот delegate для scroll down или scroll UpUITableViewCells в TableView

[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];

если вы знаете позиции UITableViewCells использовать

[tableView setContentOffset:CGPointMake(0,0) animated:YES]; 
1

Во-первых find index даты сегодняшней или любую другой дату в UITableView's dataSource, как это:

Предполагаю, date format из search date и data source date являются same

NSInteger index = NSNotFound; 
if ([tableViewArray containsObject:dateHere]) { 
    index = [tableViewArray indexOfObject:dateHere]; 
} 

Теперь прокручивается с помощью scrollToRowAtIndexPath

[yourTableView scrollToRowAtIndexPath:NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES]; 

EDIT: Используйте эти ScrollPosition вашему требованию

UITableViewScrollPositionNone, 
UITableViewScrollPositionTop,  
UITableViewScrollPositionMiddle, 
UITableViewScrollPositionBottom 
Смежные вопросы