我在tableview中显示元素数组。
现在我需要在表格视图上显示一些其他新元素。
为此,我尝试将新元素添加到数组,该数组是表视图的数据源并重新加载表。
然后它显示新添加的元素,但问题是它是在数组的最后一个元素添加,所以它显示在表视图的底部。
但我需要在表格视图的顶部显示该新值。 我怎么能这样做,任何人都可以帮助我。
提前感谢你。
(如果任何人没有提出我的问题,请允许我添加评论)。
答案 0 :(得分:3)
使用NSMutableArray insertObject: atIndex:将新项目插入数组顶部。
答案 1 :(得分:1)
创建一个新数组,其容量为旧数组+ n个新对象。添加新对象,然后遍历前一个数组并将其复制到新数组中。这样,第一个索引 - n-1将包含您添加的项目,因此显示在表格的顶部。
可能有一种更简单的方法可以做到这一点,但这种实现肯定会有效。
答案 2 :(得分:1)
您是否使用arrayByAddingObjectsFromArray:
添加新元素?
如果是这样,对象将被添加到原始数组的末尾,从而显示在表视图的末尾。
因此,不是将新数组添加到旧数组的末尾,而是将旧数组添加到新数组的末尾呢?
self.arrayForTable = [arrayWithNewElements arrayByAddingObjectsFromArray:arrayForTable];
答案 3 :(得分:0)
如果您正在使用NSMutableArray
,那么有许多功能可用于将新元素插入阵列中您想要的位置,它们就是....
将给定对象插入到给定索引处的数组内容中。
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
将给定数组中的对象插入到指定索引处的接收数组中。
- (void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes
以下是Apple文档中的代码......
NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
NSArray *newAdditions = [NSArray arrayWithObjects: @"a", @"b", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array insertObjects:newAdditions atIndexes:indexes];
NSLog(@"array: %@", array);
// Output: array: (one, a, two, b, three, four)
答案 4 :(得分:0)
在您需要在现有数据源的开头填充实体数组的用例中,请尝试以下操作:
-(NSMutableArray*)returnReorganizedArrayWithEarlierEntities:(NSArray*)theEarlierEntities{
theEarlierEntities = [[theEarlierEntities reverseObjectEnumerator] allObjects];
for(int i = 0; i < [theEarlierEntities count]; i++)
[dataSourceArray insertObject:[theEarlierEntities objectAtIndex:i] atIndex:0];
return dataSourceArray;
}
此方法的作用是颠倒您想要添加的新实体的顺序,以便它们在现有数据结构的开头正确放置(自下而上)。
干杯!
答案 5 :(得分:0)
If you still want to use Array you can do this: imagine we have an array whose type is your model(struct to class).
var yourArray = [YourModel]()
to add a new element on top of the array you can use
yourArray.insert(newElemet: Model, at: 0)
refer to this thread: Add an element to an array in Swift