我正在为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]); }