4

I have a three view controllers and a view.

one contains the main view, the other contains the customized navigation bar, and the third contains the view(aka subview of the third view controller).

when the app is loaded, navigationbar view will be visible along with the subview. Inside the subview I have a button that i want to place on top of the navigationbar view. Unfortunately i cannot do this straightforward using something like navigationitem.setrightbutton...or any other such methods (everything is coded, no nibs).

So what i am doing is setting my button frames y value to a negative value. This means that the button is out of the frame bounds of the subview, but it achieves what i want which is placing the button on top of the navigationbar.

Unfortunately no click events are passed to the button as it is outside the subview frame bounds...

I have tried overriding pointinside and hittest of the view but nothing is working.

I hope I have made myself clear. Any code that would solve this issue would be much appreciated.

4

1 回答 1

2

触摸事件仅在视图范围内传播。尽管可以将子视图放置在其父视图之外并且仍然可以看到它,但不会将事件传递给它。

处理事件的底层机制是 UIView 的以下方法:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event

此方法负责决定给定的触摸事件应该转到哪个视图。当您触摸屏幕时,会调用根视图(窗口)的 hitTest 方法,它会在其子视图上调用该方法,然后它们将在其子视图上调用该方法,依此类推。

原则上,您可以创建一个自定义窗口类并覆盖窗口中的 hitTest 方法,以强制它将事件转发到按钮,即使它超出了其父级的范围,但要正确地做到这一点是相当繁琐的。它会是这样的:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    CGRect rect = WORK_OUT_WHERE_THE_BUTTON_RECT_IS_RELATIVE_TO_THE_WINDOW;
    if (CGRectContainsPoint(rect, point))
    {
        return theButtonView;
    }
    else
    {
        return [super hitTest:point withEvent:event];
    }
}

相反,我建议您省去很多麻烦,并通过将按钮添加为导航栏的子视图来改变应用程序的工作方式,而不是使用负定位将其放置在那里。

于 2012-09-04T10:40:11.677 回答