2015-08-26 6 views
5

Ich versuche, Links zu UITextViews hinzuzufügen, so dass ich den Code in this post folgen. Der entsprechende Objective-C-Code istWie benutze ich addAttribute in Swift

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

Aber wenn ich versuche, diese in Swift 2 als

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

Ich erhalte den Fehler

nicht 'addAttribute' mit einer Argumentliste von Can aufrufen Typ '(String, Wert: String, Bereich: Bereich?)'

Was muss ich ändern? e um das zur Arbeit zu bringen?

Antwort

24

Versuchen NSString mit Bereich zu finden, anstatt 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_")) 
+0

Das Problem war, war ich mit 'NSAttributedString' statt' NSMutableAttributedString' –