【问题标题】:Scroll down uitableview to specific date向下滚动uitableview到特定日期
【发布时间】:2013-04-18 08:20:59
【问题描述】:

我想知道我是否有一个 uitable,每个表项的标题是一个日期和时间。如果我希望表格自动向下滚动到具有特定日期的单元格,我可以知道如何编码,例如今天的日期?我应该在 viewDidLoad 方法中编写什么代码?

这是我的表格代码,

@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

谢谢

【问题讨论】:

  • 您的数据源中一天会有多个日期时间吗?
  • 没有。每个单元格每天只有一个 NSDate 数据。谢谢

标签: iphone ios xcode ipad uitableview


【解决方案1】:

由于您正在处理日期,因此最好创建一个日期数组并使用 dateComponents 查找当前日期。

在这个 sn-p dates 中是一个 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];
    }
}];

编辑:

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

【讨论】:

  • 我认为您的方法很棒,但我不知道如何将其放入我的代码中。你能教我如何根据我的代码进行调整吗?谢谢
  • @Clarence 你能告诉我图片中“标题”的日期格式吗?
  • 这段代码来自表格的详细视图。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 如果您正在处理日期,最好将它们保存为业务对象中的日期,并在需要显示它们时将其转换为字符串。我已经编辑了我的答案。请看看是否可以。
  • 谢谢。现在它说没有已知的选择器 enumerateObjectsUsingBlock 调用。这是怎么回事?并且第一行“self readdatefortable”中的“self”也有错误箭头。
【解决方案2】:

首先是今天日期的find indexUITableView's dataSource 中的任何其他日期,如下所示:

我假设search datedata source date 中的date formatsame

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

现在使用scrollToRowAtIndexPath滚动

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

编辑:根据您的要求使用这些ScrollPosition

UITableViewScrollPositionNone,
UITableViewScrollPositionTop,    
UITableViewScrollPositionMiddle,   
UITableViewScrollPositionBottom

【讨论】:

    【解决方案3】:

    您必须为specific date 计算indexpath。并使用这个delegatescroll downscroll Up UITableViewCellsTableView

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

    如果你知道UITableViewCells 的位置来使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      相关资源
      最近更新 更多