我有一个表格 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/