Daniel Wagner-Hall
Daniel Wagner-Hall

Reputation: 2606

How to create an immutable NSAttributedString with a ranged attribute

How can I initialize an NSAttributedString with a ranged attribute?

As it stands, I can only work out how to add a ranged attribute after initialization, which obviously doesn't work for immutable NSAttributedString instances.

If I have an NSMutableAttributedString, I can call:

[str addAttribute:NSLinkAttributeName value:url range:range];

If I have an NSAttributedString, I can construct it:

[[NSAttributedString alloc] initWithString:str attributes:@{NSLinkAttributeName: url}];

But I can't find a way to put a range into the attributesDict.

Thanks,

Upvotes: 1

Views: 5861

Answers (2)

Shamim Hossain
Shamim Hossain

Reputation: 1760

Try this line of code.

NSString *name = @"firstname lastname";
NSAttributedString *username = [[NSAttributedString alloc] initWithString:name];

NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:username];
[mutableAttributedString addAttribute:NSLinkAttributeName value:@"www.yourdomain.com" range:NSMakeRange(0, name.length)];

Furthermore, you can another line ot text after your range

[mutableAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"other description"]];

Output

firstname lastname other description

Upvotes: 0

matt
matt

Reputation: 536047

Start with an NSMutableAttributedString. If that isn't what you have, make a mutable copy by calling mutableCopy on an NSAttributedString. Now you do have an NSMutableAttributedString.

So now do whatever you need to do.

When you are finished, if you really need an NSAttributedString, call copy on the NSMutableAttributedString to get an immutable copy. (But it is hard to see why you would need to do this, because you can always pass an NSMutableAttributedString where an NSAttributedString is expected.)

Upvotes: 8

Related Questions