Okay, so the basic idea is markdown but customizable…
Often I want a section of text to be bold, but I'm also making a byline with strange kerning, or a strikeout with different opacity, etc.
I envision a system for defining markdown codes with coresponding styles per NSAttributableString
(this class could be subclassed to persist styles, ala NSProductHeaderString
, etc)
So imagine we have a string like: "Hello, well aren't you bold." where we want to bold the last word.
With NSAttributedString
we either have to hardcode the NSRange
or do a substring look-up at run-time to generate a NSRange
to apply the bold style, or just append the bold string with its bolding attribute. None are concise or easy to understand and change.
Now imagine we define styles:
NSDictionary *styles = @{
@1 : @{
NSFontAttributeName: [UIFont fontWithName:MainFontDemiBold size:22],
NSForegroundColorAttributeName: [UIColor colorWithWhite:0 alpha:1]
}
};
…and can markdown the string like so
NSMutableStyledAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"Hello, well aren't you [1](bold)." attributes:nil];
[attrString setStyles:styles];
This would apply the set styles to that part of the string without any additional work, but the styles could be more complex to create "Hello, well aren't you bold."
NSMutableStyledAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"Hello, well aren't [2](you [1](bold))." attributes:nil];
[attrString setStyles:@{
@1 : @{
NSFontAttributeName: [UIFont fontWithName:MainFontDemiBold size:22],
NSForegroundColorAttributeName: [UIColor colorWithWhite:0 alpha:1]
},
@2 : @{
NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleThick],
NSUnderlineColorAttributeName: [UIColor redColor]
}
}];
Always using the bracked style notation could get old and would be best reserved for special cases, so typically developers could just overwrite some known defauls, while still mixing in their own numbered styles…
NSMutableStyledAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"[1](Hello), well aren't _you *bold*_" attributes:nil];
[attrString setStyles:@{
// StyleMarkdownAsterisk of course represents the * delimeter
StyleMarkdownAsterisk : @{
NSFontAttributeName: [UIFont fontWithName:MainFontDemiBold size:22]
},
StyleMarkdownLoDash : @{
NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle],
NSUnderlineColorAttributeName: [UIColor blueColor]
},
@1 : @{
NSKernAttributeName: @2.4,
}
}];