iOS 表格 View 仅在设备旋转时加载数据

标签 ios uitableview

我有一个表格 View 和一个已加载和设置的自定义单元格,但问题是除非我旋转设备,否则不会加载数据。在纵向模式下,当我第一次运行它时,那里什么也没有,一旦我以任何一种方式旋转设备,所有数据都会加载并完美运行。有什么建议吗?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"CellIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.textLabel.text = @"Hello"; return cell; 
}

数据加载-

PFQuery *query = [PFQuery queryWithClassName:@"Post"]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (!error) { 
       NSLog(@"%@", objects);
       _postsArray = [[NSArray alloc] initWithArray:objects]; 
    } else {
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an error loading the posts. Please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
       [alert show]; 
    } 
 }];
 [self.tableView reloadData];

最佳答案

您的问题是您正在异步加载数据并且在加载完成后不调用 reloadData。您确实调用了此方法,但在 block 之外,因此它会在加载完成之前立即执行。

你的数据加载方式应该是-

PFQuery *query = [PFQuery queryWithClassName:@"Post"]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (!error) { 
       NSLog(@"%@", objects);
       _postsArray = [[NSArray alloc] initWithArray:objects]; 
       dispatch_async(dispatch_get_main_queue(),^{ 
           [self.tableView reloadData];
       });
    } else {
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an error loading the posts. Please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
       dispatch_async(dispatch_get_main_queue(),^{
           [alert show]; 
       });
    } 
 }];

请注意,影响UI的操作需要在主队列上执行。

关于iOS 表格 View 仅在设备旋转时加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27870365/

相关文章:

ios - UITableViewCell 中的 UIButton 使表格滚动不流畅

ios UITableView reloadData 不增加内容高度

ios - 自定义 UITableViewCell 在触摸时突出显示

iphone - 添加为 subview 时 UITextField 不显示

ios - AdMob 原生高级广告单元 ID

ios - 自定义 UICollectionViewCell 增加内存分配

ios - 无法使用非自由模块为 iOS 编译 OpenCV

ios - UI警报 TableView 在ios7中不起作用

iphone - UITableViewCell 突出显示并隐藏分隔线

IOS/objective-C/CoreData : Delete object from NSSet