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

如何将NSMenuItem标题对齐至右侧(适配RTL语言)

实现NSMenuItem在RTL语言下自动右对齐

要让NSMenuItem的标题根据系统RTL/LTR语言自动调整对齐方式,可通过富文本属性实现,具体步骤如下:

  • 判断当前系统语言的排版方向:利用NSLocale获取语言的字符方向,确定是否为RTL
  • 为NSMenuItem设置带对齐属性的attributedTitle(默认title不支持对齐控制)

完整Objective-C实现代码

NSMenuItem* item1;
NSMenuItem* item2;

item1 = [[NSMenuItem alloc] init];
item2 = [[NSMenuItem alloc] init];

// 判断当前语言是否为RTL方向
NSLocale *currentLocale = [NSLocale currentLocale];
NSLocaleLanguageDirection langDirection = [currentLocale characterDirectionForLanguage:[currentLocale localeIdentifier]];
BOOL isRTL = (langDirection == NSLocaleLanguageDirectionRightToLeft);

// 创建段落样式,设置对齐方式
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = isRTL ? NSTextAlignmentRight : NSTextAlignmentLeft;

// 生成带对齐属性的富文本标题
NSDictionary *textAttributes = @{NSParagraphStyleAttributeName: paragraphStyle};
NSAttributedString *attributedFoo = [[NSAttributedString alloc] initWithString:@"foo" attributes:textAttributes];
NSAttributedString *attributedBar = [[NSAttributedString alloc] initWithString:@"bar" attributes:textAttributes];

// 为菜单项设置富文本标题
item1.attributedTitle = attributedFoo;
item2.attributedTitle = attributedBar;

item1.action = @selector(fooAction);
item2.action = @selector(barAction);

NSMenu *menu = [[NSMenu alloc] init];
[menu addItem:item1];
[menu addItem:item2];

额外说明

  • 如果需要支持运行时动态切换系统语言,可监听NSCurrentLocaleDidChangeNotification通知,在通知回调中重新计算排版方向并更新菜单项的attributedTitle
  • 该方案直接通过富文本控制对齐,无需依赖私有API,兼容性良好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 19:22:11