如何自动将 NSPopUpButton 的宽度减小到当前显示的文本宽度?

发布于 2025-01-12 21:04:25 字数 726 浏览 1 评论 0原文

我有一个 NSPopUpButton,默认情况下,它的宽度足以容纳其菜单中最宽文本。

现在我需要控件根据当前选择的(显示的)菜单项调整自身大小。

例如,如果菜单包含

  • A
  • XXXXXXXXXX

并且如果用户选择“A”,则控件的宽度应仅为显示“A”所需的宽度。

我该如何做到这一点? (我正在使用自动布局)

我尝试将控件的内容拥抱优先级设置为 1000,将其压缩阻力设置为 1,但这似乎没有效果。

我怀疑我需要对控件进行子类化并实现intrinsicContentSize。但是,确定 selectedItem 所需宽度的正确方法是什么?

例如,以下代码的行为符合我想要的方式,但它依赖于非法获取的值(弹出菜单指示器的额外宽度为 30 px),这是不安全的 - 例如,如果 macOS 更改了默认字体尺寸,这可能不再适合。

- (NSSize) intrinsicContentSize {
    NSSize size = super.intrinsicContentSize;
    NSPopUpButtonCell *currentCell = self.selectedCell;
    CGFloat w = currentCell.titleWidth;
    return NSMakeSize (w+30, size.height);
}

I have an NSPopUpButton that, by default, is as wide as necessary to fit the widest text in its menu.

Now I need the control to resize itself depending on the currently chosen (shown) menu item.

For example, if the menu contains

  • A
  • XXXXXXXXXX

And if the user chooses "A", then the control should be only as wide as necessary to show "A".

How do I accomplish that? (I am using Auto Layout)

I've tried to set the control's content hugging priority to 1000 and its compression resistance to 1, but that has no effect, it seems.

I suspect I need to subclass the control and implement intrinsicContentSize. But what's the proper way to determine the needed width of the selectedItem, then?

For instance, the follow code behaves the way I want it, but it relies on impirically obtained values (30 px for the extra width of the pop-up menu's indicators), which isn't safe - e.g, if macOS changes the default font size, this may not fit any more.

- (NSSize) intrinsicContentSize {
    NSSize size = super.intrinsicContentSize;
    NSPopUpButtonCell *currentCell = self.selectedCell;
    CGFloat w = currentCell.titleWidth;
    return NSMakeSize (w+30, size.height);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文