cocoa - 在 NSTextView 中显示隐藏字符

标签 cocoa special-characters hidden-characters

我正在为 Mac OS X 编写一个文本编辑器。我需要在 NSTextView 中显示隐藏字符(例如空格、制表符和特殊字符)。我花了很多时间寻找如何做到这一点,但到目前为止我还没有找到答案。如果有人能指出我正确的方向,我将不胜感激。

最佳答案

这是一个完全有效且干净的实现

@interface GILayoutManager : NSLayoutManager
@end

@implementation GILayoutManager

- (void)drawGlyphsForGlyphRange:(NSRange)range atPoint:(NSPoint)point {
  NSTextStorage* storage = self.textStorage;
  NSString* string = storage.string;
  for (NSUInteger glyphIndex = range.location; glyphIndex < range.location + range.length; glyphIndex++) {
    NSUInteger characterIndex = [self characterIndexForGlyphAtIndex: glyphIndex];
    switch ([string characterAtIndex:characterIndex]) {

      case ' ': {
        NSFont* font = [storage attribute:NSFontAttributeName atIndex:characterIndex effectiveRange:NULL];
        [self replaceGlyphAtIndex:glyphIndex withGlyph:[font glyphWithName:@"periodcentered"]];
        break;
      }

      case '\n': {
        NSFont* font = [storage attribute:NSFontAttributeName atIndex:characterIndex effectiveRange:NULL];
        [self replaceGlyphAtIndex:glyphIndex withGlyph:[font glyphWithName:@"carriagereturn"]];
        break;
      }

    }
  }

  [super drawGlyphsForGlyphRange:range atPoint:point];
}

@end

要安装,请使用:

[myTextView.textContainer replaceLayoutManager:[[GILayoutManager alloc] init]];

要查找字体字形名称,您必须转到 CoreGraphics:

CGFontRef font = CGFontCreateWithFontName(CFSTR("Menlo-Regular"));
for (size_t i = 0; i < CGFontGetNumberOfGlyphs(font); ++i) {
  printf("%s\n", [CFBridgingRelease(CGFontCopyGlyphNameForGlyph(font, i)) UTF8String]);
}

关于cocoa - 在 NSTextView 中显示隐藏字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/300086/

相关文章:

javascript - Escape String - 在 Javascript 中输出 rails 字符串

webstorm - 如何在webstorm中显示不可见的字符

objective-c - 如果我更新其中之一,则 NSArrayControllers 链接的两个 NSTable 不会同时更新

objective-c - Block_copy 是递归的吗?

cocoa - 哪条数据唯一标识一个 NSManagedObject?

objective-c - 垃圾收集器和核心基础

r - 使用 gsub 在 R 字符向量列表中用直撇号替换 curl 撇号

php - 订购印地语字符

dreamweaver - 在 Dreamweaver CS4/5 中显示不可见的制表符但不显示行尾字符?