ChatGPT解决这个技术问题 Extra ChatGPT

iphone/ipad:究竟如何使用 NSAttributedString?

是的,很多人都在谈论 iPhone/iPad 中的富文本,而且很多人都知道 NSAttributedString

但是如何使用NSAttributedString?我搜索了很多时间,没有提取线索。

我知道如何设置 NSAttributedString,那么我应该怎么做才能在 iPhone/iPad 上显示带有富文本的文本?

官方文档说它应该与CoreText.Framework一起使用,这是什么意思?

有没有这样简单的方法?

NSAttributedString *str;
.....
UILabel *label;
label.attributedString = str;
上面的答案是正确的。像这样的代码并确保将 CoreText 框架添加到链接的框架中。
谢谢,我把正确的答案留给了韦斯
Three20 看起来像一个令人印象深刻的库:github.com/facebook/three20
Three20是垃圾。
这很烦人,但我不认为这是更糟糕的事情。在过去的 6 个月里,我一直在维护一个使用 Three20 的项目……他们对内存所做的一些事情让我感到困惑。该代码非常脆弱,因为它没有以正统的方式处理内存。做他们自己提供的东西要好得多。您不太可能需要他们提供的一切。自己动手……你会学到更多,更有趣,你可能会做得更好!

R
RomanN

从 iOS 6.0 开始,您可以这样做:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Hello. That is a test attributed string."];
[str addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(3,5)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(10,7)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];
label.attributedText = str;

iOS开发程序的第一条规则是不要谈论iOS开发程序。
iOS 开发程序的第二条规则是……见第一条规则。
声明某人违反了 NDA 就是确认所提供的材料确实是在 iOS6 中,因此本身就是违反 NDA 的。您应该写类似“在不破坏 NDA 的情况下无法评论 [即将发布的版本] 中的内容”之类的内容。
此外,如果您发现自己编写了很多属性字符串,请查看此帖子/类别。使创作更容易一些。 raizlabs.com/dev/2014/03/nsattributedstring-creation-helpers
W
Wes

您应该看看 AliSoftware's OHAttributedLabel。它是 UILabel 的子类,它绘制一个 NSAttributedString 并且还提供了方便的方法来从 UIKit 类中设置 NSAttributedString 的属性。

从 repo 中提供的示例中:

#import "NSAttributedString+Attributes.h"
#import "OHAttributedLabel.h"

/**(1)** Build the NSAttributedString *******/
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"Hello World!"];
// for those calls we don't specify a range so it affects the whole string
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
// now we only change the color of "Hello"
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];


/**(2)** Affect the NSAttributedString to the OHAttributedLabel *******/
myAttributedLabel.attributedText = attrStr;
// Use the "Justified" alignment
myAttributedLabel.textAlignment = UITextAlignmentJustify;
// "Hello World!" will be displayed in the label, justified, "Hello" in red and " World!" in gray.

注意:在 iOS 6+ 中,您可以使用 UILabel 的 attributedText 属性呈现属性字符串。


没有 UIAttributedLabel 这样的东西。我认为您指的是 OHAttributedLabel。
它在 commit in November 2010 中重命名为 OHAttributedLabel。我已经更新了我的答案。
谢谢韦斯!您和编写代码的 Olivier Halligon!谢谢!
感谢@Wes 提到我的课程,感谢@DenNukem 的学分......我不知道它是如此有名;)无论如何,自从原始帖子以来我对这个课程进行了很多更新和修复,所以不要'不要忘记拉 github repo!
我在您的代码的每一行都收到错误消息。根据文档,您提供的方法在实际类中不存在,我很困惑:developer.apple.com/library/mac/#documentation/Cocoa/Reference/…
m
mattt

您应该尝试 TTTAttributedLabel。它是与 NSAttributedString 一起使用的 UILabel 的替代品,并且对于 UITableViewCells 来说足够高效。


这个类可以在下面提到的 Three20 库中找到。
不,这不是来自three20(注意3 Ts)
m
matt

有没有像 NSAttributedString *str; 这样的简单方法? UILabel *标签;标签.attributedString = str;

几乎。只需使用 CATextLayer。它有一个 string 属性,您可以将其设置为 NSAttributedString。

编辑(2012 年 11 月):当然,这一切在 iOS 6 中都发生了变化。在 iOS 6 中,您可以完全按照 OP 的要求执行操作 - 将属性字符串直接分配给标签的 attributedText


您能否更具体一些,例如提供一个示例用法?
是的,这就是我的书《iOS 5 编程》。这是书中的代码示例:github.com/mattneub/Programming-iOS-Book-Examples/blob/master/…
e
elou

iOS 6 上 UILabel 属性文本对齐的答案:使用 NSMutableAttributedString 并将 NSMutableParagraphStyle 添加到属性。像这样的东西:

NSString *str = @"Hello World!";
NSRange strRange = NSMakeRange(0, str.length);
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str];

NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setAlignment:NSTextAlignmentCenter];
[attributedStr addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:strRange];

myUILabel.attributedText = attributedStr;

P
Pete

我认为给出一个解析(简化的)HTML 字符串的示例以创建 NSAttributedString 会很有用。

它并不完整——它只处理 标签,对于初学者来说,并且不会为任何错误处理而烦恼——但希望它也是如何开始使用 NSXMLParserDelegate 的有用示例......


@interface ExampleHTMLStringToAttributedString : NSObject<NSXMLParserDelegate>

+(NSAttributedString*) getAttributedStringForHTMLText:(NSString*)htmlText WithFontSize:(CGFloat)fontSize;

@end

@interface ExampleHTMLStringToAttributedString()
@property NSString *mpString;
@property NSMutableAttributedString *mpAttributedString;

@property CGFloat mfFontSize;
@property NSMutableString *appendThisString;
@property BOOL mbIsBold;
@property BOOL mbIsItalic;
@end

@implementation ExampleHTMLStringToAttributedString
@synthesize mpString;
@synthesize mfFontSize;
@synthesize mpAttributedString;
@synthesize appendThisString;
@synthesize mbIsBold;
@synthesize mbIsItalic;

+(NSAttributedString*) getAttributedStringForHTMLText:(NSString*)htmlText WithFontSize:(CGFloat)fontSize {

    ExampleHTMLStringToAttributedString *me = [[ExampleHTMLStringToAttributedString alloc] initWithString:htmlText];
    return [me getAttributedStringWithFontSize:fontSize];
}

- (id)initWithString:(NSString*)inString {
    self = [super init];
    if (self) {
        if ([inString hasPrefix:@""]) {
          mpString = inString;
        } else {
            mpString = [NSString stringWithFormat:@"%@", inString];
        }
        mpAttributedString = [NSMutableAttributedString new];
    }
    return self;
}

-(NSAttributedString*) getAttributedStringWithFontSize:(CGFloat)fontSize {

    mfFontSize = fontSize;

    // Parse the XML
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[mpString dataUsingEncoding:NSUTF8StringEncoding]];
    parser.delegate = self;
    if (![parser parse]) {
        return nil;
    }

    return mpAttributedString;
}

-(void) appendTheAccumulatedText {
    UIFont *theFont = nil;

    if (mbIsBold && mbIsItalic) {
        // http://stackoverflow.com/questions/1384181/italic-bold-and-underlined-font-on-iphone
        theFont = [UIFont fontWithName:@"Helvetica-BoldOblique" size:mfFontSize];
    } else if (mbIsBold) {
       theFont = [UIFont boldSystemFontOfSize:mfFontSize];
    } else if (mbIsItalic) {
        theFont = [UIFont italicSystemFontOfSize:mfFontSize];
    } else {
        theFont = [UIFont systemFontOfSize:mfFontSize];
    }

    NSAttributedString *appendThisAttributedString =
    [[NSAttributedString alloc]
     initWithString:appendThisString
     attributes:@{NSFontAttributeName : theFont}];

    [mpAttributedString appendAttributedString:appendThisAttributedString];

    [appendThisString setString:@""];
}

#pragma NSXMLParserDelegate delegate

-(void)parserDidStartDocument:(NSXMLParser *)parser{
    appendThisString = [NSMutableString new];
    mbIsBold = NO;
    mbIsItalic = NO;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    if ([elementName isEqualToString:@"body"]){
    } else if ([elementName isEqualToString:@"i"]) {
      [self appendTheAccumulatedText];
        mbIsItalic = YES;
    } else if ([elementName isEqualToString:@"b"]) {
      [self appendTheAccumulatedText];
        mbIsBold = YES;
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    if ([elementName isEqualToString:@"body"]){
      [self appendTheAccumulatedText];
    } else if ([elementName isEqualToString:@"i"]) {
      [self appendTheAccumulatedText];
      mbIsItalic = NO;
    } else if ([elementName isEqualToString:@"b"]) {
        [self appendTheAccumulatedText];
        mbIsBold = NO;
    }
}

-(void)parserDidEndDocument:(NSXMLParser *)parser{
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    [appendThisString appendString:string];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
}

@end

要使用,请执行以下操作:


  self.myTextView.attributedText = [ExampleHTMLStringToAttributedString getAttributedStringForHTMLText:@"this is <b>bold</b> text" WithFontSize:self.myTextView.pointSize];

A
Ayaz

从 iOS 6.0 开始,您可以这样做:另一个示例代码。

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"This is my test code to test this label style is working or not on the text to show other user"];

[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,31)];
[str addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(61,10)];

[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:13.0] range:NSMakeRange(32, 28)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:13.0] range:NSMakeRange(65, 20)];

_textLabel.attributedText = str;

M
Mohammad Zaid Pathan

对于 Swift 使用这个,

它会使标题文本加粗,

var title = NSMutableAttributedString(string: "Title Text")

    title.addAttributes([NSFontAttributeName: UIFont(name: "AvenirNext-Bold", size: iCurrentFontSize)!], range: NSMakeRange(0, 4))

    label.attributedText = title

s
satheesh

我知道这有点晚了,但这对其他人有用,

NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString:@"string" attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];

[self.label setAttributedText:newString];

将所需的属性添加到字典并将其作为属性参数传递