【问题标题】:How to disable user interaction in a custom View如何在自定义视图中禁用用户交互
【发布时间】:2012-07-29 06:01:02
【问题描述】:

我有一个自定义视图 NSView,我想禁用用户交互,但我不确定如何执行此操作。

我的想法是:

[myView setEnabled:NO];

但这是错误的并且不起作用。我怎样才能让它对用户可见,而不是别的?

【问题讨论】:

  • 试试 [myView setUserInteractionEnabled:NO];
  • @CodersParadise:这个问题是关于 OS X,而不是 iOS。 NSView上没有这样的属性或方法...

标签: objective-c macos cocoa nsview


【解决方案1】:

NSView 没有 setEnabled: 或 setIgnoresMouseEvents:

实现the hitTest: method 以返回nil

【讨论】:

  • 我喜欢这个解决方案。实现简单,并且比禁用子视图(如果它们是控件)更健壮和可靠。
  • 这对我根本不起作用。实施 mouseDown:什么都不做是我的解决方案。
  • 这将阻止鼠标交互,但我们希望禁用任何交互,包括通过键盘(这可以通过使用 ctrl-F7 启用键盘导航,然后使用 Tab 和空格键)跨度>
【解决方案2】:

来自here

//
//  NSView-DisableSubsAdditions.m
//  Can Combine Icons
//
//  Created by David Remahl on Tue Dec 25 2001.
//  Copyright (c) 2001 Infinity-to-the-Power-of-Infinity. All rights reserved.
//

#import "NSView-DisableSubsAdditions.h"

@implementation NSView(DisableSubsAdditions)

- (void)disableSubViews
{
    [self setSubViewsEnabled:NO];
}

- (void)enableSubViews
{
    [self setSubViewsEnabled:YES];
}

- (void)setSubViewsEnabled:(BOOL)enabled
{
    NSView* currentView = NULL;
    NSEnumerator* viewEnumerator = [[self subviews] objectEnumerator];

    while( currentView = [viewEnumerator nextObject] )
    {
        if( [currentView respondsToSelector:@selector(setEnabled:)] )
        {
            [(NSControl*)currentView setEnabled:enabled];
        }
        [currentView setSubViewsEnabled:enabled];

        [currentView display];
    }
}

@end

【讨论】:

【解决方案3】:

继承NSView并添加以下方法

-(void)mouseDown:(NSEvent *)theEvent
{

}

【讨论】:

  • 完美。 hitTest: 返回 nil 对我根本不起作用——它似乎阻止了 mouseDown 被调用。所以只需使用一个空的 mouseDown:
  • 这将阻止鼠标交互,但我们希望禁用任何交互,包括通过键盘(这可以通过使用 ctrl-F7 启用键盘导航,然后使用 Tab 和空格键)跨度>
【解决方案4】:

这是 Swift 4 中的一个示例。将您的视图放入此自定义视图中。

class UserInterectionDisabledView: NSView {
    override func hitTest(_ point: NSPoint) -> NSView? {
        return nil
    }
}

【讨论】:

  • 这可能会阻止鼠标交互,但我们希望禁用任何交互,包括通过键盘。
【解决方案5】:

我认为覆盖 hitTest(_:) 并不理想,因为它会阻止其背后的所有交互。

更好的方法是让视图拒绝becomeFirstResponder。这样事件就可以发送到下一个响应者,基本上它会跳过视图。

class SubclassNSView: NSView {

  public var isUserInteractionEnabled: Bool = true

  open override func becomeFirstResponder() -> Bool {
    if isUserInteractionEnabled == false {
      return false
    } else {
      return super.becomeFirstResponder()
    }
  }
}

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多