我在NSMenuItem上使用setView:方法设置自定义视图。在这个自定义视图中,有一个图像占据整个视图。具有此自定义视图的NSMenuItem是菜单中的第一个,但问题是它不与菜单顶部齐平,有一个很大的差距,您可以在这里看到:
为什么会发生这种情况,我该如何阻止呢?
编辑
我现在使用这个代码,但是我正在使用InstallControlEventHandler的EXC_BAD_ACCESS。
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification { HIViewRef contentView; MenuRef menuRef = [statusMenu carbonMenuRef]; HIMenuGetContentView(menuRef,kThemeMenuTypePullDown,&contentView); Eventtypespec hsEventSpec[1] = { { kEventClassMenu,kEventMenuCreateFrameView } }; InstallControlEventHandler(contentView,NewEventHandlerUPP((EventHandlerProcPtr)hsMenuCreationEventHandler),GetEventTypeCount(hsEventSpec),hsEventSpec,NULL,NULL); // Get EXC_BAD_ACCESS here. } static Osstatus hsMenuContentEventHandler( EventHandlerCallRef caller,EventRef event,void* refcon ) { Osstatus err; check( GetEventClass( event ) == kEventClassControl ); check( GetEventKind( event ) == kEventControlGetFrameMetrics ); err = CallNextEventHandler( caller,event ); if ( err == noErr ) { HIViewFrameMetrics metrics; verify_noerr( GetEventParameter( event,kEventParamControlFrameMetrics,typeControlFrameMetrics,sizeof( metrics ),&metrics ) ); metrics.top = 0; verify_noerr( SetEventParameter( event,&metrics ) ); } return err; } static Osstatus hsMenuCreationEventHandler( EventHandlerCallRef caller,void* refcon ) { Osstatus err = eventNotHandledErr; if ( GetEventKind( event ) == kEventMenuCreateFrameView) { err = CallNextEventHandler( caller,event ); if ( err == noErr ) { static const Eventtypespec kContentEvents[] = { { kEventClassControl,kEventControlGetFrameMetrics } }; HIViewRef frame; HIViewRef content; verify_noerr( GetEventParameter( event,kEventParamMenuFrameView,typeControlRef,sizeof( frame ),&frame ) ); verify_noerr( HIViewFindByID( frame,kHIViewWindowContentID,&content ) ); InstallControlEventHandler( content,hsMenuContentEventHandler,GetEventTypeCount( kContentEvents ),kContentEvents,NULL ); } } return err; }
还要注意行metrics.top = 0这是应该删除顶部的间隙的行。但是我不能让它工作那么远。有谁知道为什么我会收到一个EXC_BAD_ACCESS那里。我已经创建并分配了statusMenu,所以肯定它应该工作?