Not being able to edit NSTextField on NSPopover even though Editable behavior is set

前端 未结 8 1406
别跟我提以往
别跟我提以往 2020-11-27 17:19

I have an application, which open popover with NSTextField. The text field is not editable. Behavior for text field is set to Editable. I still can

8条回答
  •  清歌不尽
    2020-11-27 17:43

    Not sure if you still need the answer, but there may be some others still looking. I found a solution on apple developer forums. Quoting the original author:

    The main problem is the way keyboard events works. Although the NSTextField (and all its superviews) receives keyboard events, it doesn't make any action. That happens because the view where the popover is atached, is in a window which can't become a key window. You can't access that window in any way, at least I couldn't. So the solution is override the method canBecomeKeyWindow for every NSWindow in our application using a category.

    NSWindow+canBecomeKeyWindow.h
    @interface NSWindow (canBecomeKeyWindow)
    
    @end
    
    NSWindow+canBecomeKeyWindow.m
    @implementation NSWindow (canBecomeKeyWindow)
    
    //This is to fix a bug with 10.7 where an NSPopover with a text field cannot be edited if its parent window won't become key
    //The pragma statements disable the corresponding warning for overriding an already-implemented method
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
    - (BOOL)canBecomeKeyWindow
    {
        return YES;
    }
    #pragma clang diagnostic pop
    
    @end
    

    That makes the popover fully resposive. If you need another window which must respond NO to canBecomeKeyWindow, you can always make a subclass.

提交回复
热议问题