How to Set "Nsbackgroundcolorattributename" on Tttattributedlabel, Ohattributedlabel or Setextview in Swift

how to set background color of range in TTTAtributedLabel

You should use kTTTBackgroundFillColorAttributeName key instead NSBackgroundColorAttributeName.

Here is the code snippet:

NSArray *keys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributeName,(id)kCTUnderlineStyleAttributeName, (id) kTTTBackgroundFillColorAttributeName, nil];
NSArray *objects = [[NSArray alloc] initWithObjects:[UIColor redColor],[NSNumber numberWithInt:kCTUnderlineStyleNone], [UIColor yellowColor], nil];
NSDictionary *linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];

self.madLibLabel.linkAttributes = linkAttributes;

[self.madLibLabel addLinkToURL:[NSURL URLWithString:@"what://"] withRange:[self.madLibLabel.text rangeOfString:@"WHAT"]];

NSBackgroundColorAttributeName doesn't seem to work on iOS 10.3

Copied from @schystz comment:

Adding NSBaselineOffsetAttributeName: 0 resolves the issue.

let paddedLineAttributed = NSMutableAttributedString(string: paddedLine, attributes: [NSFontAttributeName : newFont, NSParagraphStyleAttributeName : paragraphStyle, NSBackgroundColorAttributeName : color, NSBaselineOffsetAttributeName: 0])

Changing Background color on NSAttributedString

I think you want NSBackgroundColorAttributeName. Such as:

[mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:selectedRange];

CATextLayer NSBackGroundColorAttributeName is there a way to make it works?

The answer you pointed to is right. CATextLayer is very primitive and doesn't support this feature. Luckily, there is no need to use core text either; you can now use TextKit and just draw the string directly (and don't use CATextLayer at all).

class MyTextLayer : CALayer {
@NSCopying var string : NSAttributedString?

override func drawInContext(ctx: CGContext) {
super.drawInContext(ctx)
UIGraphicsPushContext(ctx)
string?.drawWithRect(self.bounds,
options: .UsesLineFragmentOrigin, context: nil)
UIGraphicsPopContext()
}
}


Related Topics



Leave a reply



Submit