Search code examples
objective-cnsattributedstring

NSAttributedString not displaying NSLink in Textview


I have an NSAttributedString that was made from HTML using.

NSAttributedString *decodedString = [[NSAttributedString alloc] initWithData:[encodedString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];
self.story.attributedText = decodedString;

When I run the code and view the TextView (self.story) all the text and images from the HTML show up except the hyperlinks (HTTP).

The space they occupy is there but the links aren't

example : The hyperlink is ________________ supposed to be there. just there are no ____ its just blank.

The console shows the NSAttributedString displaying

{
    NSColor = "UIDeviceRGBColorSpace 0 0 0.933333 1";
    NSFont = "<UICTFont: 0x15654c230> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
    NSKern = 0;
    NSLink = "https://www.kickstarter.com/projects/1425492550/sesame-your-key-reinvented";
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 12, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0.933333 1";
    NSStrokeWidth = 0;
    NSUnderline = 1;
}

but the "https://www.kickstarter.com/projects/1425492550/sesame-your-key-reinvented" is nowhere to be found.

Any ideas as to why this is happening and how I can fix this?


Solution

  • I am answering my own question.

    The links were getting displayed in white(on a white background) and they were unclickable so it appeared as if they were not there.

    I fixed it with this code.

    twocell.story.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor darkGrayColor]};
            NSMutableAttributedString *res = [twocell.story.attributedText mutableCopy];
            [res beginEditing];
            [res enumerateAttribute:NSUnderlineStyleAttributeName inRange:NSMakeRange(0,res.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
    
                if (value){
                    [res addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range];
                    [res endEditing];
                    [twocell.story setAttributedText:res];
                }
            }];
    

    changing the color to dark gray and adding an underline.