OmniGraffle 7 中如何获取 HorizontalTextAlignment 的名称
数据小陈
graphic.textHorizontalAlignment 是 OmniGraffle API 封装出来的枚举值,不是普通 JavaScript 对象。它上面没有 .Left 这个属性,所以读不到对齐名称;Object.values()、Object.entries()、toString() 同样拿不到 Left。比较稳妥的做法,是把它和 HorizontalTextAlignment.Left、HorizontalTextAlignment.Center、HorizontalTextAlignment.Right 逐个比较,再由一个辅助函数转成字符串。
原因
HorizontalTextAlignment.Left是 API 暴露的常量。graphic.textHorizontalAlignment.Left则是在实例上找名为Left的属性,这个属性通常不存在,结果就是undefined。Object.entries(HorizontalTextAlignment)和Object.values(graphic.textHorizontalAlignment)都为空,说明这个桥接对象没有可枚举属性。console.log打印出的[object HorizontalTextAlignment: Left]只是调试用的表示,不代表可以用.Left访问;显式调用toString()也不一定能拿到完整名称。constructor.name返回HorizontalTextAlignment只是类型名,跟当前枚举值叫什么没有关系。
直接可用的写法
function getHorizontalAlignmentName(alignment) {
if (alignment == HorizontalTextAlignment.Left) return 'Left';
if (alignment == HorizontalTextAlignment.Center) return 'Center';
if (alignment == HorizontalTextAlignment.Right) return 'Right';
return 'Unknown';
}
console.log(getHorizontalAlignmentName(graphic.textHorizontalAlignment));
业务代码里统一调用 getHorizontalAlignmentName 就行,不必在每处都写一遍判断。
以后想扩展的话,可以改成常量表:
const HORIZONTAL_ALIGNMENT_NAMES = [
[HorizontalTextAlignment.Left, 'Left'],
[HorizontalTextAlignment.Center, 'Center'],
[HorizontalTextAlignment.Right, 'Right']
];
function getHorizontalAlignmentName(alignment) {
for (const [value, name] of HORIZONTAL_ALIGNMENT_NAMES) {
if (alignment == value) return name;
}
return 'Unknown';
}
注意事项
- 不要解析
[object HorizontalTextAlignment: Left]这类字符串。它是调试输出,格式会随 OmniGraffle 版本变化,不能作为业务逻辑的依据。 - 如果当前环境里
===也能稳定返回true,优先用严格相等;否则继续用已验证可用的==。 - API 以后新增对齐值时,记得同步补进映射表,否则会落到
Unknown。 - 这类对象属于宿主环境的桥接对象,行为跟普通 JavaScript 对象不同,不要指望
Object.keys、展开运算符或JSON.stringify能正常枚举它。
备注:内容仅供参考。
