自定义UIBarButtonItem的较小活动区域

时间:2010-03-03 01:02:31

标签: iphone uinavigationcontroller uibutton uibarbuttonitem custom-view

我有一个带有自定义UIBarButtonItem的UINavigationBar(它使用UIButton作为其自定义视图)。问题是:自定义按钮的活动区域太大,如果我点击按钮外至少40个像素,它仍然会被注册为按下按钮。这会导致意外敲击。如何减少这些按钮上的活动区域?

3 个答案:

答案 0 :(得分:6)

我也注意到了这种奇怪。我发现使用容器UIView修复了这个问题。例如:

UIButton *menuButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[menuButton addTarget:self action:@selector(revealMenu:) forControlEvents:UIControlEventTouchUpInside];
[menuButton setImage:[UIImage imageNamed:@"menuIcon"] forState:UIControlStateNormal];
UIView *menuButtonContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[menuButtonContainer addSubview:menuButton];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menuButtonContainer];

答案 1 :(得分:0)

我想你没有改变自定义按钮的大小...... 试试这个...... 在“界面”构建器中,选择您想要缩小活动区域的按钮,然后按“Command + 3”或“tools - > Size inspector”,减少“W”和“H”值... 这将使自定义按钮变小,因此活动区域也会减少......

〜Raviraja

答案 2 :(得分:0)

您是通过Interface Builder添加按钮还是以编程方式执行此操作?无论哪种方式,您都可以使用这行代码来设置图像的边界:

yourButton.bounds = CGRectMake( 0, 0, yourImage.size.width, yourImage.size.height );  

如果你想要一个完整的例子,这是我在我的一个应用程序中使用的一个例子:

    UIImage *image = [UIImage imageNamed:@"audio-off.png"];
    UIButton *myMuteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myMuteButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );    
    [myMuteButton setImage:image forState:UIControlStateNormal];
    [myMuteButton addTarget:self action:@selector(mute) forControlEvents:UIControlEventTouchUpInside];    
    UIBarButtonItem *myMuteBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myMuteButton];   
    navBar.leftBarButtonItem = myMuteBarButtonItem;
    [myMuteBarButtonItem release];