UITableView没有正确重新加载



我一直有这个问题很多,其中表视图要么不加载单元格第一次或显示临时标签。在这两种情况下,当表被加载第二次(通过另一个按钮,我强迫它重新加载或通过在应用程序中的前一个视图,并返回到表)一切都显示,因为它应该。

我使用[table reloadData]viewDidAppear:方法中重新加载表,因为它在viewDidAppear:方法中不起作用,在另一种情况下,我把它放在按钮动作中。

我还使用这个方法来设置我在storyboard中放置的单元格的标签:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [contactsTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    UILabel *label = (UILabel *)[cell viewWithTag:1001];
    label.text = [Array3 objectAtIndex:indexPath.row];
    return cell;
}

编辑

我在实现下面这样声明数组:NSMutableArray * Array3;之后,在ViewDidLoad方法中,我声明了数组的其余部分:Array3 = [NSMutableArray arraywiththobjects: nil];然后我通过调用ViewDidLoad方法中的一个函数来加载数组中的元素,以填充数组中的元素。

编辑2展示更多关于如何填充数组的内容- (void)viewDidLoad {

[super viewDidLoad];
Array3 = [NSMutableArray arrayWithObjects: nil];
 [self loadArray];
}
- (void) loadArray
//populate array in here.
// I use the add object method
//  [Array3 addobject:object];
{
  1. 首先是好消息:您的方法cellForRowAtIndexPath是正确的。

  2. -viewDidAppear:-viewWillAppear中都不需要调用reloadData。如果您在视图被覆盖时修改Array3的内容,则此注释可能不成立,这是一种特殊情况

问题不在于你在哪里定义你的方法,而在于你在哪里调用它。填充Array3内容的合理位置是

required init(coder aDecoder: NSCoder!)

override func viewDidLoad()
<<p> 陷阱/strong>

另外,你需要你所有的委托方法(numberOfSectionsInTableView, numberOfRowsInSection, cellForRowAtIndexPath)返回一致的值,根据你的数组。一种简单的技术是使用数组中的条目数来驱动numberOfRowsInSection

何时使用reloadData?

reloadData的典型用法如下:

- (void)loadArray {
    //populate array in here.
    ...
    [self.tableview reloadData]; // Possibly postpone to main thread
}

让单元格标识符唯一,例如

NSString *cellIdentifier =[NSString stringWithFormate:@"%d",indexPath.row];

我认为Array3是nil当第一次加载。

我认为在Array3的初始设置中,您必须将该变量分配到内存中,然后在不同的函数中使用,如tableView:cellForIndexPath:

所以你可以用Array3 = [[NSMutableArray alloc] init];代替Array3 = [NSMutableArray arrayWithObjects: nil];

由于您在这行代码中将其作为空数组,因此您不会使用[[NSMutableArray alloc] initWithObjects: nil];,因为它实际上是相同的

最新更新