如何以编程方式将项目符号列表添加到 NSTextView

发布于 2024-11-03 20:55:40 字数 665 浏览 2 评论 0原文

这个问题可能听起来很奇怪,但我已经为此苦苦挣扎了几天。

我有一个 NSTextView,可以显示一些带有一些格式选项的文本。其中之一是能够打开/关闭所选内容或当前行的项目符号列表(最简单的列表)。

我知道 NSTextView 上有一个 orderFrontListPanel: 方法,它打开带有可用列表参数的窗口以供选择和编辑(就像在 TextView 中按菜单 -> 格式 -> 列表...)。 我已经弄清楚并实现了手动添加项目符号,并且 NSTextView 似乎与它们的行为几乎正确。我所说的“几乎”是指它保留制表符位置,在“输入”时继续列表,等等。但是有一些小故障不适合我,并且与标准实现不同。

我试图找到以编程方式设置列表的默认方法,就像通过“列表...”菜单完成的那样,但没有成功。

我寻求帮助,每一点信息都将不胜感激:)。

PS:我查看了 TextView 源代码,发现了很多有趣的内容,但没有迹象或线索如何以编程方式启用列表。

更新

仍在调查。我发现当您将 orderFrontListPanel: 发送到 NSTextView 然后选择项目符号并按 Enter 键时,不会向 NSTextView 发送任何特殊消息。这意味着项目符号列表可以在此弹出面板内的某个位置构建并直接设置到 TextView 的文本容器...

The question may sound strange but I've been struggling with it for a few days.

I have a NSTextView that can display some text with a few formatting options. One of them is the ability to turn on/off the bullet list (the easiest one) for a selection or current row.

I know that there is a orderFrontListPanel: method on NSTextView that opens the window with available list parameters to select from and edit (like in TextView when you press Menu->Format->List...).
I have already figured out and implemented adding bullets by hand and the NSTextView seems to behave with them almost correctly. By saying almost I mean that it preserves tab positions, continues the list on 'enter', etc. But there are some minor glitches that dont's suit me and differs from standart implementation.

I tried to find the default way to set lists programmatically like it is done through 'List...' menu with no luck.

I ask for help, every little bit of information will be appreciated :).

P.S.: I have looked into the TextView source code, found a lot of interesting but no sign or clue how to enable lists programmatically.

Update

Still investigating. I found that when you send orderFrontListPanel: to your NSTextView and then select bullets and press enter, no special messages are sent to NSTextView. It means that the bullet list may be constructed somewhere inside this popup panel and set directly to TextView's text container...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

删除→记忆 2024-11-10 20:55:40

以编程方式将项目符号列表添加到 NSTextView 的两种方法:

方法 1:

以下链接引导我使用第一种方法,但它是不必要的迂回,除非您想对项目符号使用一些特殊的非 Unicode 字形:

这需要:(1) 一个子类化的布局管理器,它替代某些任意字符的项目符号符号; (2) 带有firstLineHeadIndent的段落样式,一个比该缩进稍大的制表位,以及将两者结合起来的换行的headIndent。

布局管理器看起来像这样:

#import <Foundation/Foundation.h>

@interface TickerLayoutManager : NSLayoutManager {

// Might as well let this class hold all the fonts used by the progress ticker.
// That way they're all defined in one place, the init method.
NSFont *fontNormal;
NSFont *fontIndent; // smaller, for indented lines
NSFont *fontBold;

NSGlyph glyphBullet;
CGFloat fWidthGlyphPlusSpace;

}

@property (nonatomic, retain) NSFont *fontNormal;
@property (nonatomic, retain) NSFont *fontIndent; 
@property (nonatomic, retain) NSFont *fontBold;
@property NSGlyph glyphBullet;
@property CGFloat fWidthGlyphPlusSpace;

@end

#import "TickerLayoutManager.h"

@implementation TickerLayoutManager

@synthesize fontNormal;
@synthesize fontIndent; 
@synthesize fontBold;
@synthesize glyphBullet;
@synthesize fWidthGlyphPlusSpace;

- (id)init {
    self = [super init];
    if (self) {
        self.fontNormal = [NSFont fontWithName:@"Baskerville" size:14.0f];
        self.fontIndent = [NSFont fontWithName:@"Baskerville" size:12.0f];
        self.fontBold = [NSFont fontWithName:@"Baskerville Bold" size:14.0f];
        // Get the bullet glyph.
        self.glyphBullet = [self.fontIndent glyphWithName:@"bullet"];
        // To determine its point size, put it in a Bezier path and take its bounds.
        NSBezierPath *bezierPath = [NSBezierPath bezierPath];
        [bezierPath moveToPoint:NSMakePoint(0.0f, 0.0f)]; // prevents "No current point for line" exception
        [bezierPath appendBezierPathWithGlyph:self.glyphBullet inFont:self.fontIndent];
        NSRect rectGlyphOutline = [bezierPath bounds];
        // The bullet should be followed with a space, so get the combined size...
        NSSize sizeSpace = [@" " sizeWithAttributes:[NSDictionary dictionaryWithObject:self.fontIndent forKey:NSFontAttributeName]];
        self.fWidthGlyphPlusSpace = rectGlyphOutline.size.width + sizeSpace.width;
        // ...which is for some reason inexact. If this number is too low, your bulleted text will be thrown to the line below, so add some boost.
        self.fWidthGlyphPlusSpace *= 1.5; // 
    }

    return self;
}

- (void)drawGlyphsForGlyphRange:(NSRange)range 
                        atPoint:(NSPoint)origin {

    // The following prints only once, even though the textview's string is set 4 times, so this implementation is not too expensive.
    printf("\nCalling TickerLayoutManager's drawGlyphs method.");

    NSString *string = [[self textStorage] string];
    for (int i = range.location; i < range.length; i++) {
        // Replace all occurrences of the ">" char with the bullet glyph.
        if ([string characterAtIndex:i] == '>')
            [self replaceGlyphAtIndex:i withGlyph:self.glyphBullet];
    }

    [super drawGlyphsForGlyphRange:range atPoint:origin];
}

@end

将布局管理器分配给窗口/视图控制器的 awakeFromNib 中的 textview,如下所示:

- (void) awakeFromNib {

    // regular setup...

    // Give the ticker display NSTextView its subclassed layout manager.
    TickerLayoutManager *newLayoutMgr = [[TickerLayoutManager alloc] init];
    NSTextContainer *textContainer = [self.txvProgressTicker textContainer];
    // Use "replaceLM" rather than "setLM," in order to keep shared relnshps intact. 
    [textContainer replaceLayoutManager:newLayoutMgr];
    [newLayoutMgr release];
    // (Note: It is possible that all text-displaying controls in this class’s window will share this text container, as they would a field editor (a textview), although the fact that the ticker display is itself a textview might isolate it. Apple's "Text System Overview" is not clear on this point.)

}

然后添加一个类似这样的方法:

- (void) addProgressTickerLine:(NSString *)string 
                   inStyle:(uint8_t)uiStyle {

    // Null check.
    if (!string)
        return;

    // Prepare the font.
    // (As noted above, TickerLayoutManager holds all 3 ticker display fonts.)
    NSFont *font = nil;
    TickerLayoutManager *tickerLayoutMgr = (TickerLayoutManager *)[self.txvProgressTicker layoutManager];
    switch (uiStyle) {
        case kTickerStyleNormal:
            font = tickerLayoutMgr.fontNormal;
            break;
        case kTickerStyleIndent:
            font = tickerLayoutMgr.fontIndent;
            break;
        case kTickerStyleBold:
            font = tickerLayoutMgr.fontBold;
            break;
        default:
            font = tickerLayoutMgr.fontNormal;
            break;
    }


    // Prepare the paragraph style, to govern indentation.    
    // CAUTION: If you propertize it for re-use, make sure you don't mutate it once it has been assigned to an attributed string. (See warning in class ref.)
    // At the same time, add the initial line break and, if indented, the tab.
    NSMutableParagraphStyle *paragStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; // ALLOC
    [paragStyle setAlignment:NSLeftTextAlignment]; // default, but just in case
    if (uiStyle == kTickerStyleIndent) {
        // (The custom layout mgr will replace ‘>’ char with a bullet, so it should be followed with an extra space.)
        string = [@"\n>\t" stringByAppendingString:string];
        // Indent the first line up to where the bullet should appear.
        [paragStyle setFirstLineHeadIndent:15.0f];
        // Define a tab stop to the right of the bullet glyph.
        NSTextTab *textTabFllwgBullet = [[NSTextTab alloc] initWithType:NSLeftTabStopType location:15.0f + tickerLayoutMgr.fWidthGlyphPlusSpace];
        [paragStyle setTabStops:[NSArray arrayWithObject:textTabFllwgBullet]];  
        [textTabFllwgBullet release];
        // Set the indentation for the wrapped lines to the same place as the tab stop.
        [paragStyle setHeadIndent:15.0f + tickerLayoutMgr.fWidthGlyphPlusSpace];
    }
    else {
        string = [@"\n" stringByAppendingString:string];
    }


    // PUT IT ALL TOGETHER.
    // Combine the above into a dictionary of attributes.
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                            font, NSFontAttributeName, 
                            paragStyle, NSParagraphStyleAttributeName, 
                            nil];
    // Use the attributes dictionary to make an attributed string out of the plain string.
    NSAttributedString *attrs = [[NSAttributedString alloc] initWithString:string attributes:dict]; // ALLOC
    // Append the attributed string to the ticker display.
    [[self.txvProgressTicker textStorage] appendAttributedString:attrs];

    // RELEASE
    [attrs release];
    [paragStyle release];

}

测试一下:

NSString *sTicker = NSLocalizedString(@"First normal line of ticker should wrap to left margin", @"First normal line of ticker should wrap to left margin");
[self addProgressTickerLine:sTicker inStyle:kTickerStyleNormal];
sTicker = NSLocalizedString(@"Indented ticker line should have bullet point and should wrap farther to right.", @"Indented ticker line should have bullet point and should wrap farther to right.");
[self addProgressTickerLine:sTicker inStyle:kTickerStyleIndent];
sTicker = NSLocalizedString(@"Try a second indented line, to make sure both line up.", @"Try a second indented line, to make sure both line up.");
[self addProgressTickerLine:sTicker inStyle:kTickerStyleIndent];
sTicker = NSLocalizedString(@"Final bold line", @"Final bold line");
[self addProgressTickerLine:sTicker inStyle:kTickerStyleBold];

你会得到这个:

在此处输入图像描述

方法 2:

但项目符号是常规 Unicode 字符,十六进制 2022。因此您可以将其放入直接输入字符串,并获得精确的测量值,如下所示:

    NSString *stringWithGlyph = [NSString stringWithUTF8String:"\u2022"];
    NSString *stringWithGlyphPlusSpace = [stringWithGlyph stringByAppendingString:@" "];
    NSSize sizeGlyphPlusSpace = [stringWithGlyphPlusSpace sizeWithAttributes:[NSDictionary dictionaryWithObject:self.fontIndent forKey:NSFontAttributeName]];
    self.fWidthGlyphPlusSpace = sizeGlyphPlusSpace.width;

因此不需要自定义布局管理器。只需如上所述设置 paragStyle 缩进,并将文本字符串附加到包含行 return + 项目符号字符 + 空格(或 + tab,在这种情况下您仍然需要该制表位)的字符串。

使用空格,会产生更紧凑的结果:

在此处输入图像描述

想要使用项目符号以外的字符吗?这是一个很好的 Unicode 图表:http://www.danshort.com/unicode/

Two methods of programmatically adding a bulleted list to an NSTextView:

Method 1:

The following links led me to this first method, but it’s unnecessarily roundabout unless you want to use some special non-Unicode glyph for the bullet:

This requires: (1) a subclassed layout manager that substitutes the bullet glyph for some arbitrary character; and (2) a paragraph style with a firstLineHeadIndent, a tab stop slightly bigger than that indent, and a headIndent for wrapped lines that combines the two.

The layout manager looks like this:

#import <Foundation/Foundation.h>

@interface TickerLayoutManager : NSLayoutManager {

// Might as well let this class hold all the fonts used by the progress ticker.
// That way they're all defined in one place, the init method.
NSFont *fontNormal;
NSFont *fontIndent; // smaller, for indented lines
NSFont *fontBold;

NSGlyph glyphBullet;
CGFloat fWidthGlyphPlusSpace;

}

@property (nonatomic, retain) NSFont *fontNormal;
@property (nonatomic, retain) NSFont *fontIndent; 
@property (nonatomic, retain) NSFont *fontBold;
@property NSGlyph glyphBullet;
@property CGFloat fWidthGlyphPlusSpace;

@end

#import "TickerLayoutManager.h"

@implementation TickerLayoutManager

@synthesize fontNormal;
@synthesize fontIndent; 
@synthesize fontBold;
@synthesize glyphBullet;
@synthesize fWidthGlyphPlusSpace;

- (id)init {
    self = [super init];
    if (self) {
        self.fontNormal = [NSFont fontWithName:@"Baskerville" size:14.0f];
        self.fontIndent = [NSFont fontWithName:@"Baskerville" size:12.0f];
        self.fontBold = [NSFont fontWithName:@"Baskerville Bold" size:14.0f];
        // Get the bullet glyph.
        self.glyphBullet = [self.fontIndent glyphWithName:@"bullet"];
        // To determine its point size, put it in a Bezier path and take its bounds.
        NSBezierPath *bezierPath = [NSBezierPath bezierPath];
        [bezierPath moveToPoint:NSMakePoint(0.0f, 0.0f)]; // prevents "No current point for line" exception
        [bezierPath appendBezierPathWithGlyph:self.glyphBullet inFont:self.fontIndent];
        NSRect rectGlyphOutline = [bezierPath bounds];
        // The bullet should be followed with a space, so get the combined size...
        NSSize sizeSpace = [@" " sizeWithAttributes:[NSDictionary dictionaryWithObject:self.fontIndent forKey:NSFontAttributeName]];
        self.fWidthGlyphPlusSpace = rectGlyphOutline.size.width + sizeSpace.width;
        // ...which is for some reason inexact. If this number is too low, your bulleted text will be thrown to the line below, so add some boost.
        self.fWidthGlyphPlusSpace *= 1.5; // 
    }

    return self;
}

- (void)drawGlyphsForGlyphRange:(NSRange)range 
                        atPoint:(NSPoint)origin {

    // The following prints only once, even though the textview's string is set 4 times, so this implementation is not too expensive.
    printf("\nCalling TickerLayoutManager's drawGlyphs method.");

    NSString *string = [[self textStorage] string];
    for (int i = range.location; i < range.length; i++) {
        // Replace all occurrences of the ">" char with the bullet glyph.
        if ([string characterAtIndex:i] == '>')
            [self replaceGlyphAtIndex:i withGlyph:self.glyphBullet];
    }

    [super drawGlyphsForGlyphRange:range atPoint:origin];
}

@end

Assign the layout manager to the textview in your window/view controller’s awakeFromNib, like this:

- (void) awakeFromNib {

    // regular setup...

    // Give the ticker display NSTextView its subclassed layout manager.
    TickerLayoutManager *newLayoutMgr = [[TickerLayoutManager alloc] init];
    NSTextContainer *textContainer = [self.txvProgressTicker textContainer];
    // Use "replaceLM" rather than "setLM," in order to keep shared relnshps intact. 
    [textContainer replaceLayoutManager:newLayoutMgr];
    [newLayoutMgr release];
    // (Note: It is possible that all text-displaying controls in this class’s window will share this text container, as they would a field editor (a textview), although the fact that the ticker display is itself a textview might isolate it. Apple's "Text System Overview" is not clear on this point.)

}

And then add a method something like this:

- (void) addProgressTickerLine:(NSString *)string 
                   inStyle:(uint8_t)uiStyle {

    // Null check.
    if (!string)
        return;

    // Prepare the font.
    // (As noted above, TickerLayoutManager holds all 3 ticker display fonts.)
    NSFont *font = nil;
    TickerLayoutManager *tickerLayoutMgr = (TickerLayoutManager *)[self.txvProgressTicker layoutManager];
    switch (uiStyle) {
        case kTickerStyleNormal:
            font = tickerLayoutMgr.fontNormal;
            break;
        case kTickerStyleIndent:
            font = tickerLayoutMgr.fontIndent;
            break;
        case kTickerStyleBold:
            font = tickerLayoutMgr.fontBold;
            break;
        default:
            font = tickerLayoutMgr.fontNormal;
            break;
    }


    // Prepare the paragraph style, to govern indentation.    
    // CAUTION: If you propertize it for re-use, make sure you don't mutate it once it has been assigned to an attributed string. (See warning in class ref.)
    // At the same time, add the initial line break and, if indented, the tab.
    NSMutableParagraphStyle *paragStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; // ALLOC
    [paragStyle setAlignment:NSLeftTextAlignment]; // default, but just in case
    if (uiStyle == kTickerStyleIndent) {
        // (The custom layout mgr will replace ‘>’ char with a bullet, so it should be followed with an extra space.)
        string = [@"\n>\t" stringByAppendingString:string];
        // Indent the first line up to where the bullet should appear.
        [paragStyle setFirstLineHeadIndent:15.0f];
        // Define a tab stop to the right of the bullet glyph.
        NSTextTab *textTabFllwgBullet = [[NSTextTab alloc] initWithType:NSLeftTabStopType location:15.0f + tickerLayoutMgr.fWidthGlyphPlusSpace];
        [paragStyle setTabStops:[NSArray arrayWithObject:textTabFllwgBullet]];  
        [textTabFllwgBullet release];
        // Set the indentation for the wrapped lines to the same place as the tab stop.
        [paragStyle setHeadIndent:15.0f + tickerLayoutMgr.fWidthGlyphPlusSpace];
    }
    else {
        string = [@"\n" stringByAppendingString:string];
    }


    // PUT IT ALL TOGETHER.
    // Combine the above into a dictionary of attributes.
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                            font, NSFontAttributeName, 
                            paragStyle, NSParagraphStyleAttributeName, 
                            nil];
    // Use the attributes dictionary to make an attributed string out of the plain string.
    NSAttributedString *attrs = [[NSAttributedString alloc] initWithString:string attributes:dict]; // ALLOC
    // Append the attributed string to the ticker display.
    [[self.txvProgressTicker textStorage] appendAttributedString:attrs];

    // RELEASE
    [attrs release];
    [paragStyle release];

}

Test it out:

NSString *sTicker = NSLocalizedString(@"First normal line of ticker should wrap to left margin", @"First normal line of ticker should wrap to left margin");
[self addProgressTickerLine:sTicker inStyle:kTickerStyleNormal];
sTicker = NSLocalizedString(@"Indented ticker line should have bullet point and should wrap farther to right.", @"Indented ticker line should have bullet point and should wrap farther to right.");
[self addProgressTickerLine:sTicker inStyle:kTickerStyleIndent];
sTicker = NSLocalizedString(@"Try a second indented line, to make sure both line up.", @"Try a second indented line, to make sure both line up.");
[self addProgressTickerLine:sTicker inStyle:kTickerStyleIndent];
sTicker = NSLocalizedString(@"Final bold line", @"Final bold line");
[self addProgressTickerLine:sTicker inStyle:kTickerStyleBold];

You get this:

enter image description here

Method 2:

But the bullet is a regular Unicode char, at hex 2022. So you can put it in the string directly, and get an exact measurement, like this:

    NSString *stringWithGlyph = [NSString stringWithUTF8String:"\u2022"];
    NSString *stringWithGlyphPlusSpace = [stringWithGlyph stringByAppendingString:@" "];
    NSSize sizeGlyphPlusSpace = [stringWithGlyphPlusSpace sizeWithAttributes:[NSDictionary dictionaryWithObject:self.fontIndent forKey:NSFontAttributeName]];
    self.fWidthGlyphPlusSpace = sizeGlyphPlusSpace.width;

So there is no need for the custom layout manager. Just set the paragStyle indentations as above, and append your text string to a string holding the line return + bullet char + space (or + tab, in which case you’ll still want that tab stop).

Using a space, this produced a tighter result:

enter image description here

Want to use a character other than the bullet? Here’s a nice Unicode chart: http://www.danshort.com/unicode/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文