【发布时间】:2011-02-10 11:59:05
【问题描述】:
我想创建一个带有自定义图像的 UIBarButtonItem,但我不想要 iPhone 添加的边框,因为我的图像有一个特殊的边框。
它和后退按钮一样,但是一个前进按钮。
这个应用程序是一个内部项目,所以我不在乎苹果是否拒绝或批准它或喜欢它:-)
如果我使用 UIBarButtonItem 的 initWithCustomView:v 属性,我可以做到:
UIImage *image = [UIImage imageNamed:@"right.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage: [image stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateNormal];
[button setBackgroundImage: [[UIImage imageNamed: @"right_clicked.png"] stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateHighlighted];
button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height);
[button addTarget:self action:@selector(AcceptData) forControlEvents:UIControlEventTouchUpInside];
UIView *v=[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
[v addSubview:button];
UIBarButtonItem *forward = [[UIBarButtonItem alloc] initWithCustomView:v];
self.navigationItem.rightBarButtonItem= forward;
[v release];
[image release];
这可行,但如果我必须在 10 个视图中重复此过程,这不是 DRY。
我想我必须继承,但是什么?
- NSView ?
- UIBarButtonItem ?
谢谢,
问候,
【问题讨论】:
-
感谢分享您的代码,这就是我所需要的 :) .
-
大家,我使用了 San 在 2 月 6 日提供的答案。整合到我的 Storyboard 中花了整整 5 分钟,而且效果很好。 Selector 属性位于 IB 的 Connections Inspector 下。控制从 UIButton 拖动到 ViewController 对象,方法将弹出。点击你想要的方法,你就完成了。唯一剩下的就是一些代码清理。使用 btnXXXXX.hidden 隐藏和取消隐藏以替换 barbuttonitem = nil。但是这种方法很简单,也很干净。
标签: ios iphone uibarbuttonitem