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

如何替换macOS中已弃用的NSToolbarItem自定义视图尺寸约束?

替代NSToolbarItem弃用的minSize/maxSize的解决方案

直接给自定义视图添加尺寸约束即可替代已弃用的ToolbarItem属性,具体操作如下:

  • 给自定义视图添加尺寸约束:在初始化你的运行时绘制自定义视图(NSView子类)时,手动添加宽度和高度的约束,指定最小、最大或固定尺寸。示例代码:

    // 自定义视图实例化
    CustomToolbarView *customView = [[CustomToolbarView alloc] init];
    customView.translatesAutoresizingMaskIntoConstraints = NO;
    
    // 设置最小尺寸约束
    [customView.widthAnchor constraintGreaterThanOrEqualToConstant:40.0].active = YES;
    [customView.heightAnchor constraintGreaterThanOrEqualToConstant:30.0].active = YES;
    
    // 设置最大尺寸约束(按需添加)
    [customView.widthAnchor constraintLessThanOrEqualToConstant:80.0].active = YES;
    [customView.heightAnchor constraintLessThanOrEqualToConstant:30.0].active = YES;
    
  • 关联到ToolbarItem:将添加好约束的自定义视图赋值给NSToolbarItem的view属性,无需再设置ToolbarItem的minSize/maxSize:

    NSToolbarItem *toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:@"CustomItem"];
    toolbarItem.view = customView;
    
  • 关键注意点:

    • 必须将自定义视图的translatesAutoresizingMaskIntoConstraints设为NO,确保手动添加的约束生效,避免自动生成的约束干扰。
    • 如果自定义视图重写了intrinsicContentSize提供固有尺寸,约束会和固有尺寸配合工作:比如最小宽度约束生效时,若视图固有宽度大于最小值,将使用固有宽度;若小于,则被约束拉至最小值。

内容的提问来源于stack exchange,提问作者Aarhus88

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:15:56