You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS Ventura下setMaxSize已弃用,如何设置NSToolbarItem尺寸?

解决NSToolbarItem弃用setMaxSize后约束不生效的问题

问题描述

使用[toolbarItem setMaxSize: NSMakeSize(24,24)]时可正常控制工具栏项大小,但该方法已被弃用。尝试直接给工具栏项的视图添加布局约束却无效果,代码如下:

NSView *itemView = toolbarItem.view;
itemView.translatesAutoresizingMaskIntoConstraints = NO;

NSLayoutConstraint *widthConstraint = [itemView.widthAnchor constraintEqualToConstant: 24];
NSLayoutConstraint *heightConstraint = [itemView.heightAnchor constraintEqualToConstant: 24];

widthConstraint.active = YES;
heightConstraint.active = YES;

解决方案

直接修改toolbarItem.view的约束不会生效,因为NSToolbar会接管该视图的布局管理。正确处理方式有两种:

方式一:给内部自定义视图添加约束

如果工具栏项使用了自定义视图,将自定义视图添加到toolbarItem.view中,给自定义视图设置宽高约束,让父视图自适应子视图大小:

// 假设customView是你的自定义视图
NSView *customView = [[NSView alloc] init];
customView.translatesAutoresizingMaskIntoConstraints = NO;
[toolbarItem.view addSubview:customView];

// 添加约束固定自定义视图尺寸并居中
[NSLayoutConstraint activateConstraints:@[
    [customView.widthAnchor constraintEqualToConstant:24],
    [customView.heightAnchor constraintEqualToConstant:24],
    [customView.centerXAnchor constraintEqualToAnchor:toolbarItem.view.centerXAnchor],
    [customView.centerYAnchor constraintEqualToAnchor:toolbarItem.view.centerYAnchor]
]];

方式二:设置视图的固有内容大小

如果没有自定义视图,可直接修改toolbarItem.view的固有内容大小,让工具栏根据该尺寸布局:

NSView *itemView = toolbarItem.view;
itemView.intrinsicContentSize = NSMakeSize(24, 24);

内容的提问来源于stack exchange,提问作者Andreas Löw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:55:22