簡體   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