Search code examples
iostextnsattributedstringstrikethrough

NSAttributedString Strike attribute not working


I know this question has been asked many times, but none of the answers I read helped me to fix my problem...

In my iOS app, I'm generating a PDF file using default frameworks (UIGraphicsBeginPDFContextToFile...). Everything works fine, I can change text colors, underlying styles, etc.

But I don't manage to strike a string.

Here's my code:

[toBeConfirmedText addAttributes:@{ NSBaselineOffsetAttributeName: @(0), NSStrikethroughStyleAttributeName: @(NSUnderlineStyleThick), NSStrikethroughColorAttributeName: [UIColor redColor] } range:NSMakeRange(0, toBeConfirmedText.length)];

But that does not work...

Does anyone has an idea?


Solution

  • I should add a comment that your code has no problem in Xcode 10. But because I need to add test codes, so you may treat it as an answer.

            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"myTest.pdf"];
            BOOL result =    UIGraphicsBeginPDFContextToFile(filePath, CGRectZero, nil);
    
            UIGraphicsBeginPDFPage();
    
            NSMutableAttributedString * toBeConfirmedText = [[NSMutableAttributedString alloc]initWithString:@"mytest"];
    
            [toBeConfirmedText addAttributes:@{ NSBaselineOffsetAttributeName: @(0), NSStrikethroughStyleAttributeName: @(NSUnderlineStyleThick), NSStrikethroughColorAttributeName: [UIColor redColor] } range:NSMakeRange(0, toBeConfirmedText.length)];
    
            [toBeConfirmedText drawInRect: CGRectMake(0, 0, 600, 200)];
            UIGraphicsEndPDFContext();