Touch Bar,如何添加可滚动的按钮列表?

Ber*_*rnd 0 macos objective-c swift nstouchbar

我想在我的应用程序的触摸栏中显示一个可滚动的按钮列表,类似于Safari在键入地址时显示收藏夹的方式.

滚动视图似乎不是标准的TouchBar控件之一.您使用哪种控件?

小智 8

TouchBar实际上支持NSScrollView(https://developer.apple.com/reference/appkit/nstouchbar#2587738).

NSScrubber旨在成为项目的选择器,类似于分段控件,但具有可滚动列表的附加好处.NSScrubber还管理着自己突出显示的状态,并会吃掉触摸事件.您可以通过将它们弹出到滚动视图中来获取NSButton的水平可滚动列表.这是使用约束创建NSCustomTouchBarItem的快速示例:

  NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:CGRectMake(0, 0, 400, 30)];

  NSMutableDictionary *constraintViews = [NSMutableDictionary dictionary];
  NSView *documentView = [[NSView alloc] initWithFrame:NSZeroRect];

  NSString *layoutFormat = @"H:|-8-";
  NSSize size = NSMakeSize(8, 30);

  for (int i = 0; i <= 8; i++) {
    NSString *objectName = [NSString stringWithFormat:@"button%@",@(i)];
    NSButton *button = [NSButton buttonWithTitle:objectName
                                          target:nil
                                          action:nil];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    [documentView addSubview:button];

    // Constraint information
    layoutFormat = [layoutFormat stringByAppendingString:[NSString stringWithFormat:@"[%@]-8-", objectName]];
    [constraintViews setObject:button forKey:objectName];
    size.width += 8 + button.intrinsicContentSize.width;
  }

  layoutFormat = [layoutFormat stringByAppendingString:[NSString stringWithFormat:@"|"]];

  NSArray *hConstraints = [NSLayoutConstraint constraintsWithVisualFormat:layoutFormat
                                                                  options:NSLayoutFormatAlignAllCenterY
                                                                  metrics:nil
                                                                    views:constraintViews];

  [documentView setFrame:NSMakeRect(0, 0, size.width, size.height)];
  [NSLayoutConstraint activateConstraints:hConstraints];
  scrollView.documentView = documentView;

  NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:@"com.TouchBar.scrollButtons"];
  item.view = scrollView;
Run Code Online (Sandbox Code Playgroud)