在NSTableView中禁用滚动

erk*_*diz 10 macos scroll objective-c nstableview nsscrollview

有没有一种简单的方法来禁用NSTableView的滚动.

似乎没有任何属性 [myTableView enclosingScrollView][[myTableView enclosingScrollView] contentView]禁用它.

tit*_*nus 17

这适用于我:子类NSScrollView,设置和覆盖通过:

- (id)initWithFrame:(NSRect)frameRect; // in case you generate the scroll view manually
- (void)awakeFromNib; // in case you generate the scroll view via IB
- (void)hideScrollers; // programmatically hide the scrollers, so it works all the time
- (void)scrollWheel:(NSEvent *)theEvent; // disable scrolling

@interface MyScrollView : NSScrollView
@end

#import "MyScrollView.h"

@implementation MyScrollView

- (id)initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame:frameRect];
    if (self) {
        [self hideScrollers];
    }

    return self;
}

- (void)awakeFromNib
{
    [self hideScrollers];
}

- (void)hideScrollers
{
    // Hide the scrollers. You may want to do this if you're syncing the scrolling
    // this NSScrollView with another one.
    [self setHasHorizontalScroller:NO];
    [self setHasVerticalScroller:NO];
}

- (void)scrollWheel:(NSEvent *)theEvent
{
    // Do nothing: disable scrolling altogether
}

@end
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.

  • 更准确地说:NSTableView不是NSScrollView,而是包含在其中。因此,您必须将封闭的NSScrollView更改为此自定义类。 (2认同)

pro*_*ero 9

感谢@titusmagnus的答案,但我做了一个修改,以便在"禁用"scrollView嵌套在另一个scrollView中时不打破滚动:当光标位于内部边界内时,无法滚动外部scrollView滚动视图.如果你这样做......

- (void)scrollWheel:(NSEvent *)theEvent
{
    [self.nextResponder scrollWheel:theEvent];
    // Do nothing: disable scrolling altogether
}
Run Code Online (Sandbox Code Playgroud)

...然后"禁用"scrollView将滚动事件传递到外部scrollView,它的滚动不会卡在其子视图中.


Ben*_*ero 8

在我看来,这是最好的解决方案:

斯威夫特4

import Cocoa

@IBDesignable
@objc(BCLDisablableScrollView)
public class DisablableScrollView: NSScrollView {
    @IBInspectable
    @objc(enabled)
    public var isEnabled: Bool = true

    public override func scrollWheel(with event: NSEvent) {
        if isEnabled {
            super.scrollWheel(with: event)
        }
        else {
            nextResponder?.scrollWheel(with: event)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


只需更换任何NSScrollViewDisablableScrollView(或者BCLDisablableScrollView,如果你还在使用ObjC),你就大功告成了.只需isEnabled在代码或IB中设置,它将按预期工作.

这样做的主要优点是嵌套滚动视图; 在没有将事件发送到下一个响应者的情况下禁用子项也将在光标位于禁用的子项上时有效地禁用父项.

以下列出了这种方法的所有优点:

  • ✅禁用滚动
    • ✅以编程方式执行,默认情况下正常运行
  • ✅不中断滚动父视图
  • ✅InterfaceBuilder集成
  • ✅直接替换 NSScrollView
  • ✅Swift和Objective-C兼容