我有一个带有两个 View 的导航栏应用程序:父 View 和 subview 。在 subview 中,我在右上角添加一个按钮,如下所示:
- (void)viewDidLoad {
UIBarButtonItem *tempButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"lock-unlocked.png"] style:UIBarButtonItemStylePlain target:self action:@selector(lockScreen)];
self.navigationItem.rightBarButtonItem = tempButton;
[tempButton release];
}
单击该按钮时,我想更改此 rightBarButtonItem 的图像并禁用 leftBarButtonItem (由 Controller 自动添加)。按钮基本上有两种状态:锁定和解锁。
问题1: 我能找到如何更改图像的唯一方法是使用新图像创建一个新的 UIButtonItem 并将 rightBarButtonItem 替换为该新图像。但我想知道是否有一种方法可以只更改图像而不创建新的 UIBarButtonItem。如果我继续创建新的 UIBarButtonItem,是否会造成内存泄漏?
问题2: 如何获取 self.navigationItem.leftBarButtonItem 并禁用/启用它?我不会手动创建它,它是由 Controller 自动为我创建的。我在 UIBarButtonItem 上没有看到任何方法/属性来启用/禁用用户与其交互。
最佳答案
问题1:在界面中声明UIBarButtonItem *tempButton
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
UIBarButtonItem *tempButton;
}
@property (nonatomic, retain) UIBarButtonItem *tempButton;
并在实现中综合它。
@synthesize tempButton;
在 viewDidLoad 中创建与现在类似的对象。
- (void)viewDidLoad {
tempButtom = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"lock-unlocked.png"] style:UIBarButtonItemStylePlain target:self action:@selector(lockScreen)];
self.navigationItem.rightBarButtonItem = tempButton;
}
但不要在这里释放它,而是在通常位于底部的 dealloc 方法中释放它。
然后当调用lockScreen时执行
tempButton.image = [UIImage imageNamed:@"myImage.png"]
恐怕我没有问题 2 的答案!
关于iphone - 如何更改图像并禁用 UIBarButtonItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/536399/