Почему происходит сбой rightBarButtonItem? - PullRequest
0 голосов
/ 05 марта 2012

Почему я получаю сбой "Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]" после установки rightBarButtonItem?

В моем приложении справа расположены три кнопки, одна из которых должна чередоваться с systemEditButton.Поэтому я установил кнопки с помощью rightBarButtonItems (обратите внимание на «s»), а затем изменил правую, используя rightBarButtonItem, когда это необходимо.

С 5.0 Apple позволяет устанавливать несколько элементов в leftBarButtonItemsи rightBarButtonItems из NavigationBar.В нем также говорится, что вы можете изменить внешний с помощью leftBarButtonItem и rightBarButtonItem соответственно («Первый элемент в массиве также можно установить с помощью свойства rightBarButtonItem»).

Работает нормально в первый раз, но затем вылетает, когда я возвращаю исходную кнопку.Хуже того, он не возражает, когда я его установил, он падает позже во время анимации UINavigationBar layoutSubViews.Проверка rightBarButtonItems после установки rightBarButtonItems показывает, что он корректно обновил массив, но он вылетает во время компоновки.

1 Ответ

0 голосов
/ 06 марта 2012

Что ж, я подтвердил это с помощью тестовой программы (см. Ниже) и отправил отчет об ошибках в Apple. Обходной путь - прочитать массив Items и передать его обратно с обновленным нулевым элементом.

//
//  ViewController.m
//  testBarButton
//
//  Created by Hugh Mackworth on 3/4/12.
//  Copyright (c) 2012 PineTree Software. All rights reserved.
//
#import "ViewController.h"
//#import <UIKit/UIKit.h>
//
//@interface ViewController : UIViewController {
//    
//@private
//    UIBarButtonItem * itemA;
//}
//
//@property (strong, nonatomic) UIBarButtonItem * itemA;
//
//@end

@implementation ViewController

@synthesize itemA;  //@property (strong, nonatomic) UIBarButtonItem * itemA;

-(void) reportButtons {
    NSLog (@"buttons:  %@",self.navigationItem.rightBarButtonItems);
}

-(void) itemA:(id) sender {
    NSLog(@"itemA hit");
   [self reportButtons];
}

-(void) itemB:(id) sender {
    NSLog(@"itemB hit");
    self.navigationItem.rightBarButtonItem = self.itemA;
    [self reportButtons];
}

-(void) itemC:(id) sender {
    NSLog(@"itemC hit");
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self reportButtons];
}

-(void) loadView {
    self.view = [[UIView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
    self.itemA = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Alternative Edit",@"")
                                                              style:UIBarButtonItemStyleBordered
                                                             target:self
                                                             action:@selector(itemA:)]; 
    UIBarButtonItem *itemB = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"B-Hit Second",@"")
                                                              style:UIBarButtonItemStyleBordered
                                                             target:self
                                                             action:@selector(itemB:)]; //fix with itemB2:
    UIBarButtonItem *itemC = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"C-Hit First",@"")
                                                              style:UIBarButtonItemStyleBordered
                                                             target:self
                                                             action:@selector(itemC:)]; //fix with itemC2:
    NSArray *rightItems = [NSArray arrayWithObjects: 
                           self.itemA,
                           itemB,
                           itemC,
                           nil];
    self.navigationItem.rightBarButtonItems = rightItems;
    [self reportButtons];                       

}

-(void) swapRightItem: (UIBarButtonItem *) newRightItem {
    NSMutableArray * newRightItems = [self.navigationItem.rightBarButtonItems mutableCopy];
    [newRightItems replaceObjectAtIndex:0 withObject: newRightItem];
    self.navigationItem.rightBarButtonItems = newRightItems;
    [self reportButtons];
}

-(void) itemB2:(id) sender {
    NSLog(@"itemB2 hit");
    [self swapRightItem:self.itemA];
}

-(void) itemC2:(id) sender {
    NSLog(@"itemC2 hit");
    [self swapRightItem:self.editButtonItem];
}

@end

//APP DELEGATE:
/*
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController * viewController = [[ViewController alloc] init];
    UINavigationController *watchNavController= [[UINavigationController alloc] initWithRootViewController:viewController ];

    self.window.rootViewController = watchNavController;
    [self.window makeKeyAndVisible];
    return YES;
}
*/
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...