【发布时间】:2015-01-26 19:19:56
【问题描述】:
我在我的应用上实现了 SWReveal 控件。为了触发动作,我有一个带有自定义视图的 UIBarButtonItem。好吧,一切正常,但我注意到,即使在远离图像(大约 44 像素宽的图像......并且点击最大 100 像素)时,我也可以触发事件。
我已经搜索了一段时间,找到了最好的解决方案(定义自定义按钮并使用“initWithCustomView”实例化 UIBarButtonItem)
这是我之前的代码:
UIBarButtonItem *revealButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"reveal-icon"] style:UIBarButtonItemStylePlain target:_revealController action:@selector(revealToggle:)];
self.navigationItem.leftBarButtonItem = revealButtonItem;
以及带有“解决方案”的代码:
//create the image for your button, and set the frame for its size
UIImage *image = [UIImage imageNamed:@"reveal-icon"];
CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
//init a normal UIButton using that image
UIButton* button = [[UIButton alloc] initWithFrame:frame];
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:_revealController action:@selector(revealToggle:) forControlEvents:UIControlEventTouchUpInside];
//finally, create your UIBarButtonItem using that button
UIBarButtonItem* revealButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = revealButtonItem;
通过后面的代码,我知道我有一个正确大小的按钮(我设置了 backgroundColor,并检查了按钮的正确大小),但在远离按钮点击时仍然触发动作。
¿有什么想法吗?
提前谢谢你。
【问题讨论】:
-
不回答您的问题,但是:您为什么要这样做? iOS 增加条形按钮项的可触摸区域是有原因的。您似乎在那里有一个菜单按钮(作为左侧唯一的按钮),我真的看不出明确使可触摸区域小于默认值的任何优势。并且:在设备上测试这个,而不是在模拟器上!!
-
如果你的可触摸区域只有大约 20x20pt(只是猜测你图标的大小),你的用户会杀了你.. ;-)
-
我已经阅读了苹果的 Humans 指南,我并没有假装做这么小的按钮,但是,正如我在问题中所说,问题是可选择区域比 Apple 大得多按钮的实际大小(您可以在其他著名的应用程序中看到相同的问题,在该应用程序中,您有一个自定义图像用作按钮,但在远离它的地方点击会触发操作。但在 facebook 应用程序中,您会看到此行为已更正. :)
-
@raululm 我的
leftBarButtonItem遇到了完全相同的问题,您解决了还是接受了? :)
标签: ios uibarbuttonitem