我的代码如下:
#import "TestTableViewController.h"
@interface TestTableViewController ()
@property (nonatomic,strong) NSMutableArray *testDataArray;
@end
@implementation TestTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.testDataArray = [[NSMutableArray alloc] init];
for(int i = 0; i < 20; i++){
[self.testDataArray addObject:[NSString stringWithFormat:@"TestString - %@",@(i)]];
}
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.testDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"testCell" forIndexPath:indexPath];
cell.textLabel.text = [self.testDataArray objectAtIndex:indexPath.row];
return cell;
}
- (IBAction)insertNewElement:(UIBarButtonItem *)sender
{
[self.testDataArray insertObject:@"AAAAAA" atIndex:0];
[self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]
withRowAnimation:UITableViewRowAnimationAutomatic];
}
如您所见,代码非常简单。 故事板也是标准的:
但是当我选择第三个细胞并插入新细胞时(新插入的细胞没有分隔线):
我找到了一个解决方案,但它存在问题。首先它使用私有API,其次我不确定这是一个好习惯:
- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *subview in self.contentView.superview.subviews) {
if ([NSStringFromClass(subview.class) hasSuffix:@"SeparatorView"]) {
subview.hidden = NO;
}
}
}
有可能,这是Apple的错误吗?
答案 0 :(得分:2)
我建议您使用方法实现(例如
)对应用程序的简化版进行一点改动- (IBAction)insertNewElement:(UIBarButtonItem *)sender
{
//Update 1:
[self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedrow inSection:0] animated:NO];
[self.testDataArray insertObject:@"AAAAAA" atIndex:0];
[self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]
withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedrow+1 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
} //selectedrow define in your .m file as NSInteger.
愿这对你有帮助!!
答案 1 :(得分:1)
在其他答案的基础上,我将使用begin和endUpdates代替
- (IBAction)insertNewElement:(UIBarButtonItem *)sender
{
[self.tableView beginUpdates];
[self.testDataArray insertObject:@"AAAAAA" atIndex:0];
[self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]
withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedrow+1 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
[self.tableView endUpdates];
}