Мой uitableview
вызывает reloaddata
при изменении ориентации устройства (имеет смысл, так как количество отображаемых ячеек изменяется, вызывается в виде макета, насколько я мог понять из документации) , но для меня это проблематично, потому что я выполняю загрузку в фоновом режиме, и я не хочу, чтобы некоторые из файлов неожиданно появлялись. Есть ли способ остановить поведение по умолчанию и позволить мне перезагружать вручную, когда захочу?Остановить UITableView от перезагрузки данных при изменении ориентации
EDIT: Я попытаюсь объяснить лучше. в верхней части моего табличного представления у меня есть кнопка с именем «sync», которая запускает запрос синхронизации с сервера, этот запрос синхронизации сначала получает объект JSON, который содержит информацию, которую я хотел бы отображать в виде таблицы, но каждый из uitableview
Элементы представляют собой файл, который я загружаю из Интернета.
Во время загрузки файлов у меня есть индикатор активности на экране, только когда файлы заканчиваются загрузкой. Я хочу перезагрузить таблицу. Проблема заключается в том, что UITableview
автоматически вызывает reloaddata
, когда пользователь меняет ориентацию, поэтому ячейки заполняются информацией из json перед загрузкой загруженных файлов.
код:
@implementation BIDManageFilesViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newDataFinishedDownloading) name:kBIDContentManagerContentDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newDataStartedDownloading:) name:kBIDContentManagerStartedDownloadingContent object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentAlreadyUpToDate) name:kBIDContentUpToDate object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentStartingSync) name:kBIDContentStartingSync object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentEndingSync) name:kBIDContentEndingSync object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(singleDownloadFinished) name:kBIDFinishedDownloadingSingleContent object:nil];
self.navigationController.navigationBarHidden = NO;
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Sync"
style:UIBarButtonItemStyleDone target:self action:@selector(Sync)];
self.navigationItem.leftBarButtonItem = leftButton;
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Display Mode"
style:UIBarButtonItemStyleDone target:self action:@selector(dismissSelf)];
self.navigationItem.rightBarButtonItem = rightButton;
self.navigationItem.title = @"Content Manager";
self.navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectZero];
[self.view addSubview:_navigationBar];
[self.navigationBar pushNavigationItem:self.navigationItem animated:NO];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
}
-(void)layoutNavigationBar{
if([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait || [[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown)
{
self.navigationBar.frame = CGRectMake(0, self.tableView.contentOffset.y, self.view.frame.size.width, self.topLayoutGuide.length + 44);
}
else
{
self.navigationBar.frame = CGRectMake(0, self.tableView.contentOffset.y, self.view.frame.size.height, self.topLayoutGuide.length + 44);
}
NSLog(@"width: %f", self.view.frame.size.width);
NSLog(@"height: %f", self.view.frame.size.height);
self.tableView.contentInset = UIEdgeInsetsMake(self.navigationBar.frame.size.height, 0, 0, 0);
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//no need to call super
[self layoutNavigationBar];
}
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[self layoutNavigationBar];
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}
-(void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
[self layoutNavigationBar];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
-(void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
self.navigationController.navigationBarHidden = YES;
}
-(void)newDataStartedDownloading: (NSNotification *)notif
{
self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
_hud.labelText = @"Downloading...";
_hud.detailsLabelText = [NSString stringWithFormat:@"1/%@",[notif.userInfo objectForKey:@"downloadFileNumber"]];
}
-(void)singleDownloadFinished
{
NSString *currentText = _hud.detailsLabelText;
NSArray *subStrings = [currentText componentsSeparatedByString:@"/"];
NSInteger downloadsPlusOne = [[subStrings objectAtIndex:0] integerValue]+1;
NSString *newTextForLabel = [NSString stringWithFormat:@"%d/%@", downloadsPlusOne, [subStrings objectAtIndex:1]];
_hud.detailsLabelText = newTextForLabel;
}
-(void)newDataFinishedDownloading
{
_thereIsNewInfo = TRUE;
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self.tableView reloadData];
[[NSNotificationCenter defaultCenter] postNotificationName:kBIDnewDownloadedContentReadyToBeDispayedNotification object:nil userInfo:nil];
}
-(void)contentAlreadyUpToDate
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sync Alert"
message:@"Files Are Already Up To Date"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
}
-(void)contentStartingSync
{
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = @"Syncing...";
}
-(void)contentEndingSync
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
-(void)Sync
{
[AppDelegate.appContentManager downloadContent];
}
-(void)dismissSelf
{
if (![AppDelegate.appContentManager subsetArrayFromFileArrayWithNonVidContentThatShouldDisplay] && ![AppDelegate.appContentManager subsetArrayFromFileArrayWithVideoContentThatShouldDisplay]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Files to Display"
message:@"Please update or enable content"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
return;
}
else if ([AppDelegate.appContentManager subsetArrayFromFileArrayWithNonVidContentThatShouldDisplay])
{
[self dismissViewControllerAnimated:YES completion:Nil];
}
else
{
[self performSegueWithIdentifier:@"goToVideos" sender:self];
}
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"goToVideos"])
{
((BIDViewController *)segue.destinationViewController).stackedByManager = TRUE;
}
}
@end
Я не понимаю, что такое табличное представление связано с загрузкой файлов. Не могли бы вы объяснить проблему немного лучше или показать какой-то код? – Krumelur