gpt4 book ai didi

objective-c - 以编程方式获取 TextEdit 中所选文本的字体名称

转载 作者:行者123 更新时间:2023-12-03 17:56:59 34 4
gpt4 key购买 nike

经过两个月的尝试,我找到了如何从 TextEdit(或任何 NSTextView)的任何文本范围中获取 AttributedString。我的代码如下:

AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement,
kAXFocusedUIElementAttribute, (CFTypeRef*)&focussedElement);
if (error != kAXErrorSuccess) {
println("Could not get focussed element");
}
else {
AXValueRef selectedRangeValue = NULL;
AXError getSelectedRangeError =
AXUIElementCopyAttributeValue(focussedElement,
kAXSelectedTextRangeAttribute, (CFTypeRef*)&selectedRangeValue);
if (getSelectedRangeError == kAXErrorSuccess) {
CFRange selectedRange;
AXValueGetValue(selectedRangeValue, kAXValueCFRangeType,
&selectedRange);
AXValueRef attributedString = NULL;
AXError getAttrStrError =
AXUIElementCopyParameterizedAttributeValue(focussedElement,
kAXAttributedStringForRangeParameterizedAttribute, selectedRangeValue,
(CFTypeRef*)&attributedString);
CFRelease(selectedRangeValue);

if (getAttrStrError == kAXErrorSuccess)
{
CFAttributedStringRef attrStr = (CFAttributedStringRef)attributedString;

CFTypeRef value = CFAttributedStringGetAttribute(
attrStr, 0, kAXFontTextAttribute, NULL);

println("value: %X", value); // value is not NULL, but I can't obtain font name from it.

CFRelease(attributedString);
}
else
{
println("Could not get attributed string for selected range");
}
}
else {
println("Could not get selected range");
}
}
if (focussedElement != NULL)
CFRelease(focussedElement);
CFRelease(systemWideElement);

我正确获取了CFAttributedStringRef(我可以从中获取长度或纯文本),但无法获取字体名称

注意:

下面代码返回的值不为NULL:

CFTypeRef value = CFAttributedStringGetAttribute(
attrStr, 0, kAXFontTextAttribute, NULL);

该值不能假定为 CTFontRef 或 CGFontRef、ATSFontRef...(导致异常)。

我还尝试用 kCTFontAttributeName 代替 kAXFontTextAttribute,但返回 NULL。

非常感谢。

最佳答案

与键kAXFontTextAttribute关联的值似乎是一个CFDictionaryRef。请参阅AXTextAttributedString documentation .

关于objective-c - 以编程方式获取 TextEdit 中所选文本的字体名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11717878/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com