[SOLVED] How to use addAttribute in Swift

Issue

I’m trying to add links to UITextViews, so I am following the code in this post. The relevant Objective-C code is

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];
[attributedString addAttribute:NSLinkAttributeName
                         value:@"username://marcelofabri_"
                         range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];

But when I try this in Swift 2 as

var attributedString = NSMutableAttributedString(string: "This is an example by @marcelofabri_")
attributedString.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: attributedString.string.rangeOfString("/marcelofabri_"))

I get the error

Cannot invoke ‘addAttribute’ with an argument list of type ‘(String, value: String, range: Range?)’

What do I need to change to get this to work?

Solution

Try using NSString to find range instead of Swift String:

var attributedString = NSMutableAttributedString(string: "This is an example by @marcelofabri_")
attributedString.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: (attributedString.string as NSString).rangeOfString("/marcelofabri_"))

Answered By – egor.zhdan

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *