以编程方式添加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)
。无论如何,在此先感谢您的帮助!
最佳答案
[[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
会被系统忽略。 (但不应该是它不起作用的原因。)
关于objective-c - 如何以编程方式添加UIBarButtonItem?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5440389/