繁体   English   中英

NSTextView使用数组制作粗体文本

[英]NSTextView making bold text using an array

我有一个具有以下结构的数组:

(
    [0] = (
         [0] = @"Title string"
         [1] = @"Some content string"
    )
    [1] = (
         [0] = @"Title string"
         [1] = @"Some content string"
    )
    [2] = (
         [0] = @"Title string"
         [1] = @"Some content string"
    )
    ...
)

依此类推,等等。

我的目标是尝试将所有内容合并为一个字符串以显示在NSTextField中,并使每个标题字符串加粗。 因此,如果输出,上面的代码将看起来像这样。


标题字符串
一些内容字符串

标题字符串
一些内容字符串

标题字符串
一些内容字符串


我的第一个问题是如何在某些文本为粗体的情况下制作单个字符串? 我的第二个问题是我怎样才能将该字符串发送给NSTextField?


到目前为止,这是我所做的。
我试过使用NSMutableAttributedString使字符串像这样:

 NSMutableAttributedString *contentString = [NSMutableAttributedString alloc]; for (int i=0; i<[result count]; i++) { [contentString addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"HelveticaNeue-Bold" size:16.0] range:NSRangeFromString(result[i][0])]; } 

但是我无法弄清楚如何在字符串中添加其他内容,或者仅尝试打印该字符串,因为在尝试将其显示在NSTextField中时遇到了此错误。

[self->contentView attributedString:contentString];

所以我尝试了这个,但是出现了另一个错误

 [self->contentView attributedString:contentString]; 

'NSTextView'的可见@interface没有声明选择器'attributedString'

设法找到一种使其运作的方法

NSMutableAttributedString *contentString = [NSMutableAttributedString alloc];

for (int i=0; i<[result count]; i++) {    
    NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@\n\n", result[i][0], result[i][1]]];
    NSDictionary *attributes = @{
        NSFontAttributeName : [NSFont fontWithName:@"HelveticaNeue-Bold" size:12.0]
    };
    NSString *subtitle = [NSString stringWithFormat:@"%@", result[i][0]];

    [resultString setAttributes:attributes range:NSMakeRange(0, [subtitle length])];
    [contentString appendAttributedString:resultString];
}

[self->content setString:@""];
[[self->content textStorage] appendAttributedString:contentString];

解决方案位于代码的最后一行。 所有要做的事情不是将数据传递给setString ,而是使用textStorage并将对象传递给它。 (我认为我的术语正确)

Bue yeah希望以后对任何人有帮助!

这个怎么样...

NSMutableAttributedString *contentString = [[NSMutableAttributedString alloc] init];
for (int i = 0; i < [result count]; i++) {
    NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@\n\n", result[i][0], result[i][1]]];
    [resultString addAttribute:NSFontAttributeName
            value:[NSFont fontWithName:@"HelveticaNeue-Bold" size:16.0]
            range:NSRangeFromString(result[i][0])];
    [contentString appendAttributedString:resultString];
}

有关您其他代码的一些说明。 确保将您的[NSMutableAttributedString alloc]与类似[[NSMutableAttributedString alloc] init]的初始化进行匹配

您应该认识到NSMutableAttributedString不是NSString的子类,而是NSObject ,因此setString:不是可供您使用的方法。

NSTextView使用insertText:来设置它的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM