Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use addAttribute in Swift

Tags:

ios

swift

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?

like image 755
Suragch Avatar asked Aug 26 '15 13:08

Suragch


2 Answers

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_"))
like image 143
egor.zhdan Avatar answered Oct 02 '22 14:10

egor.zhdan


You are using Range rather than NSRange as required. Have a look at:

NSRange from Swift Range?

like image 38
Yarneo Avatar answered Oct 02 '22 13:10

Yarneo