TwitterのようにハッシュタグをUITextViewでリンク化したいのでこのページを参考に、
https://stackoverflow.com/questions/34294064/how-to-make-uitextview-detect-hashtags
このコードを設定しました
swift
1UITextViewHashtagExtension.swift 2import UIKit 3extension UITextView { 4 func resolveTags(){ 5 let nsText:NSString = self.text as NSString! 6 7 // this needs to be an array of NSString. String does not work. 8 let words:[String] = nsText.components(separatedBy: " ") 9 10 // you can't set the font size in the storyboard anymore, since it gets overridden here. 11 let attrs = [ 12 NSFontAttributeName : UIFont.systemFont(ofSize: 17.0) 13 ] 14 15 // you can staple URLs onto attributed strings 16 let attrString = NSMutableAttributedString(string: nsText as String, attributes:attrs) 17 18 // tag each word if it has a hashtag 19 for word in words { 20 21 // found a word that is prepended by a hashtag! 22 // homework for you: implement @mentions here too. 23 if word.hasPrefix("#") { 24 25 // a range is the character position, followed by how many characters are in the word. 26 // we need this because we staple the "href" to this range. 27 let matchRange:NSRange = nsText.range(of: word as String) 28 29 // convert the word from NSString to String 30 // this allows us to call "dropFirst" to remove the hashtag 31 var stringifiedWord:String = word as String 32 33 // drop the hashtag 34 stringifiedWord = String(stringifiedWord.characters.dropFirst()) 35 36 // check to see if the hashtag has numbers. 37 // ribl is "#1" shouldn't be considered a hashtag. 38 let digits = NSCharacterSet.decimalDigits 39 40 if (stringifiedWord.rangeOfCharacter(from: digits) != nil) { 41 // hashtag contains a number, like "#1" 42 // so don't make it clickable 43 44 } else { 45 // set a link for when the user clicks on this word. 46 // it's not enough to use the word "hash", but you need the url scheme syntax "hash://" 47 // note: since it's a URL now, the color is set to the project's tint color 48 attrString.addAttribute(NSLinkAttributeName, value: "hash://" + stringifiedWord, range: matchRange) 49 } 50 } 51 52 self.attributedText = attrString 53 } 54 55} 56}
swift
1ViewController.swift 2class ViewController: UIViewController, UITextViewDelegate { 3 @IBOutlet weak var textView: UITextView! 4 override func viewDidLoad() { 5 super.viewDidLoad() 6 7 self.textView.text = "#テスト" 8 self.textView.resolveTags() 9 //self.textView.resolveAtTags() 10 textView.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.red] 11 12 } 13 func textView(_ textView: UITextView, 14 shouldInteractWith URL: URL, 15 in characterRange: NSRange, 16 interaction: UITextItemInteraction) -> Bool { 17 18 print(URL) 19 20 return false 21 } 22 23}
実行し、ハッシュタグ部分をタップするとこのエラーが出てクラッシュしてしまいます
正しく実行するにはどのようにすれば良いのでしょうか
ご教授をお願いいたします