UITableViewController исчезает после переключения на другую вкладку и обратно

Я застрял посреди странной проблемы. Часами. У меня есть вкладка навигации с 4 контроллерами представления. Проблема в том, что 4-й MiMaAdditionalController является контроллером таблицы. Последний показывает себя только с первого раза, с правильно построенным tableview, элементами appstore и так далее. Когда я нажимаю на любую из предыдущих вкладок (контроллеры представления отображаются в порядке) и снова возвращаюсь на 4-ю вкладку, табличное представление отсутствует, а заголовок вкладки имеет правильный «Дополнительный» заголовок... Я пробовал все с xib, с созданным вручную табличным представлением и т. д., но проблема стоит, и я не знаю решения. Вот код для запуска приложения и MiMaAdditionalController.

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
glbMainViewController = [[MiMaMainController alloc] init];
glbAdditionalController = [[MiMaAdditionalController alloc]init];
glbSettingViewController = [[MiMaSettingsController alloc] init];
glbWebServicesListController = [[MiMaWebServicesList alloc] init];
glbTabBarController = [[UITabBarController alloc] init];

self.glbTabBarController.viewControllers = @[glbMainViewController, glbWebServicesListController, glbSettingViewController, glbAdditionalController];

//TabBar customization and initialization...
UITabBar *myTabBar = [glbTabBarController tabBar];
[myTabBar setBackgroundColor:[UIColor clearColor]];

glbRootNavController = [[UINavigationController alloc] initWithRootViewController:glbTabBarController];

self.window.rootViewController = glbRootNavController;

// Override point for customization after application launch.
self.window.backgroundColor = [UIColor lightGrayColor];
[self.window makeKeyAndVisible];
return YES;

MiMaAdditionalController.h

@interface MiMaAdditionalController : UITableViewController


@property (strong, nonatomic) UIRefreshControl *refreshControl;
@property (nonatomic, strong) UIBarButtonItem *glbBarButtonRestore;

- (void)reload;

@end

MiMaAdditionalController.m

#import "MiMaAdditionalController.h"

@interface MiMaAdditionalController ()
{
  NSSet *_listOfProducts;
  NSArray *_appStoreProducts;
  NSNumberFormatter *_priceFormatter;
}
@end

@implementation MiMaAdditionalController

@synthesize refreshControl, glbBarButtonRestore;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
  return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) viewWillAppear:(BOOL)animated
{
  self.tabBarController.title = NSLocalizedString(@"Additional", @"Additional");
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(productPurchased:) name:MiMaProductPurchasedNotification object:nil];
}

- (void) viewWillDisappear:(BOOL)animated
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) productPurchased:(NSNotification *) notification
{
  NSString *productIdentifier = notification.object;
  [_appStoreProducts enumerateObjectsUsingBlock:^(SKProduct *product, NSUInteger idx, BOOL *stop)
   {
     if ([product.productIdentifier isEqualToString:productIdentifier])
     {
       [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
       *stop = YES;
     }
   }
   ];
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  [self.navigationController setNavigationBarHidden:NO];
  self.navigationController.navigationBar.translucent = NO;
  self.edgesForExtendedLayout = UIRectEdgeNone;
  self.refreshControl = [[UIRefreshControl alloc] init];
  [self.refreshControl addTarget:self.tableView action:@selector(reload) forControlEvents:UIControlEventValueChanged];
  [self reload];
  [self.refreshControl beginRefreshing];

  _priceFormatter = [[NSNumberFormatter alloc] init];
  [_priceFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
  [_priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
  NSString *restoreButtonText = NSLocalizedString(@"Restore purchase", "Restore purchase");
  glbBarButtonRestore = [MiMaGlobal createToolBarButtonItemWithTitle:restoreButtonText withTarget:self
                                                      withAction:@selector(restoreTapped:)
                                                 withButtonWidth:0 withButtonHeight:0
                                                withImageMouseUp:@"restore40x40" withImageMouseOver:@"restore40x40green" andShowTitle:NO];
  [self.tabBarController.navigationItem setRightBarButtonItems:@[glbBarButtonRestore] animated:YES];
}

// Add new method
- (void)restoreTapped:(id)sender {
  [[MiMa12frameInApp sharedInstance] restoreCompletedTransactions];
}
// 4
- (void)reload {
  [[MiMa12frameInApp sharedInstance] requestProductsWithCompletionHandler:^(BOOL success,
                                                                            NSArray *products) {
    if (success) {
      _appStoreProducts = products;
      [self.tableView reloadData];
    }
    [self.refreshControl endRefreshing];
  }];
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  if (section == 0) {
      return [_appStoreProducts count];
  } else
    return 4;

}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
  return 2;
}

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
  switch (section) {
    case 0:
    {
      return NSLocalizedString(@"In-app purchase", "In-app purchase");
      break;
    }
    case 1:
    {
      return NSLocalizedString(@"Additional actions", "Additional actions");
      break;
    }
    default:
      return @"";
      break;
  }
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *cellIdent = @"cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
  if (cell ==nil)
  {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdent];
  }
  if (indexPath.section == 0)
  {
     SKProduct *product = (SKProduct *) [_appStoreProducts objectAtIndex:[indexPath row]];
  cell.textLabel.text = product.localizedTitle;
  [_priceFormatter setLocale:product.priceLocale];
  cell.detailTextLabel.text = [_priceFormatter stringFromNumber:product.price];
  if ([[MiMa12frameInApp sharedInstance] productPurchased:product.productIdentifier])
  {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    cell.accessoryView = nil;
  } else
  {
    UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    buyButton.frame = CGRectMake(0, 0, 72, 37);
    [buyButton setTitle:NSLocalizedString(@"Buy", @"Buy") forState:UIControlStateNormal];
    buyButton.tag = indexPath.row;
    [buyButton addTarget:self action:@selector(buyButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.accessoryView = buyButton;
  }
  } else if (indexPath.section == 1)
  {
    if (cell == nil) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdent];
    }

    if (indexPath.row == 0) {
      cell.textLabel.text = NSLocalizedString(@"Tell a Friend", "");
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else if (indexPath.row == 1) {
      cell.textLabel.text = NSLocalizedString(@"Gift This App", "");
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else if (indexPath.row == 2) {
      cell.textLabel.text = NSLocalizedString(@"Rate in App Store", "");
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else if (indexPath.row == 3) {
      cell.textLabel.text = NSLocalizedString(@"About this app", "");
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
  }
  return cell;
}

- (void) buyButtonTapped:(id) sender
{
  UIButton *buyButton = (UIButton *) sender;
  SKProduct *product = _appStoreProducts[buyButton.tag];
  NSLog(NSLocalizedString(@"Buying %@...", @"Buying %@..."), product.productIdentifier);
  [[MiMa12frameInApp sharedInstance] buyProduct:product];
}

- (void)didReceiveMemoryWarning
{
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (indexPath.section == 1) {
    if (indexPath.row == 0) {
      if ([[iTellAFriend sharedInstance] canTellAFriend]) {
        UINavigationController* tellAFriendController = [[iTellAFriend sharedInstance] tellAFriendController];
        [self presentViewController:tellAFriendController animated:YES completion:nil];
      }
    } else if (indexPath.row == 1) {
      [[iTellAFriend sharedInstance] giftThisAppWithAlertView:YES];
    } else if (indexPath.row == 2) {
      [[iTellAFriend sharedInstance] rateThisAppWithAlertView:YES];
    } else if (indexPath.row == 3) {
      [self showAbout];
    }


    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
  }

}

- (void)showAbout
{
  //TO DO...
  NSLog(@"About");
}

@end

person Mickey Jason    schedule 30.08.2014    source источник


Ответы (1)


После долгого путешествия я, наконец, «решил» проблему. Я отказываюсь от существующего и создаю новый UITableViewController без XIB. После переноса того же существующего кода на новый контроллер все работает отлично. В чем была настоящая причина такой продолжительной головной боли, я так и не узнал.

person Mickey Jason    schedule 03.09.2014