2

以编程方式添加 UIBarButtonItem 的正确方法是什么?在我的情况下,我试图添加一个,rightBarButtonItem并且我一直在控制器层次结构中跳跃,但我似乎无法让按钮显示在任何地方。

这是我当前的代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationItem setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithImage:[[UIImage alloc] initWithContentsOfFile:@"Barcode-White.png"] style:UIBarButtonItemStylePlain target:self action:@selector(scanEquipment:)] autorelease]];
}

我希望有人能引导我走向正确的方向。我试图从中调用它的控制器是 3 个级别。所以,UITabBarController-> UIViewController (Settings, 1st level)-> UIViewController (Vehicle, 2nd level)-> UIViewController (Inventory, 3rd level)

无论如何,提前感谢您的帮助!

4

1 回答 1

1

[[UIImage alloc] initWithContentsOfFile:@"Barcode-White.png"]可能行不通。initWithContentsOfFile 获取图像文件的完整路径,而不仅仅是文件名。这可能就是问题所在;它返回 nil,这导致整个按钮构造函数返回 nil。

(此外,您通过调用 init 方法而不释放或自动释放来泄漏此图像。)

试试[UIImage imageNamed:@"Barcode-White"]吧,它会在应用程序的资源中查找图像文件,并且有额外的好处,即只加载一次图像,然后无论调用多少次都将其缓存在内存中:

http://developer.apple.com/library/ios/documentation/uikit/reference/UIImage_Class/Reference/Reference.html#//apple_ref/occ/clm/UIImage/imageNamed

除此之外,它看起来应该可以工作......

此外,导航栏项目的样式始终为UIBarButtonItemStyleBordered. 尝试将其设置为UIBarButtonItemStylePlain将被系统忽略。(但不应该是它不起作用的原因。)

于 2011-03-26T05:16:38.137 回答