我有以下方法将单元格添加到tableview。我希望添加的单元格位于底部,但是现在它将它添加到顶部。有什么建议吗?
addEvent方法:
-(void)addEvent
{
Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
routine.name=entered;
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
NSLog(@"%@", error);
[eventsArray insertObject:routine atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
viewDidLoad中
- (void)viewDidLoad
{
if (managedObjectContext == nil)
{
managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
self.navigationItem.rightBarButtonItem = editButton;
[editButton release];
[super viewDidLoad];
}
答案 0 :(得分:0)
可能使用[eventsArray addObject:]而不是insertObject:atIndex:
另外,你应该可以使用[self.routineTableView reloadData];假设您以正常方式设置了表视图控制器,而不是手动插入行。
答案 1 :(得分:0)
0
是第一个索引。作为一项规则(世界某处可能存在一些例外)与索引有关的事情,从0开始。而像count
这样的事情从1开始。
因此,如果您的数组中包含1个对象,则数组的计数将为1
,对象将位于索引0
。
当你使用0时,对于你indexPath
的行和部分,你要告诉它把它放在桌面视图的顶部。
所以让你最后4行代码如下:
[eventsArray addObject:routine];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.routineTableView reloadData];
NSInteger lastSection = [self.routineTableView numberOfSections] -1;
[self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.routineTableView numberOfRowsInSection:lastSection]-1 inSection:lastSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
答案 2 :(得分:0)
您问题的具体答案是您的表有一个数组作为数据源,并且您在数组的开头添加一个新项。因此,当重新加载表时,新单元格位于顶部。
为了更深入地了解,我建议您至少理解以下主题:
用作数据源的常用数据类型(主要是数组和字典)
表视图的工作原理(例如tableView.dataSource和tableView.delegate是什么)
当dataSource发生变化时重新加载表格的方法(你做了什么但不总是你想要的)