2017-12-10 27 views
0

アトリビュートされた文字列内に2つのリンクを表示し、それぞれのリンクが異なる色で表示したい。私はそれをする方法を理解していません。常に1つの色しか設定されません。私はこれを数日間苦労してきましたが、それを動作させる方法はまだ分かりません。誰か知っていますか? 2色は設定できますが、リンクは設定できません!すべてのリンクは同じ色です。UITextView 2つのリンクがあり、それぞれ異なる色で動作しないテキスト

これは私の全体の実装です:私はこのNSMutableAttributedString extensionはあなたがあなたのリンクの範囲を合わせるあなたのそれぞれの色を割り当てることができますNSRegularExpressionを使用して、このArticle.

から適応プロジェクトで使用している(UPDATE)

var checkIn = "" 
    var friends = "" 

//MARK: Change Name Color/Font/Add a second LABEL into the same label 
    func setColorAndFontAttributesToNameAndCheckIn() { 
     let nameSurname = "\(postAddSetup.nameSurname.text!)" 
     checkIn = "" 
     friends = "" 

     if selectedFriends.count == 0 { 
      print("we have no friends...") 
      friends = "" 
     } else if selectedFriends.count == 1 { 
      print("we have only one friend...") 
      friends = "" 
      friends = " is with \(self.firstFriendToShow)" 
     } else if selectedFriends.count > 1 { 
      print("we have more than one friend...") 
      friends = "" 
      friends = " is with \(self.firstFriendToShow) and \(self.numberOfFriendsCount) more" 
     } 

     if checkIn == "" { 
      checkIn = "" 
     } 

     var string = postAddSetup.nameSurname.text 
     string = "\(nameSurname)\(friends)\(checkIn) " 

     let attributedString = NSMutableAttributedString(string: string!) 
     attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14), range: (string! as NSString).range(of: nameSurname)) 

     attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 13), range: (string! as NSString).range(of: checkIn)) 
     attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 13), range: (string! as NSString).range(of: friends)) 

     attributedString.addLink("checkIn", linkColor: UIColor.darkGray, text: checkIn) 
     attributedString.addLink("tagFriends", linkColor: UIColor.red, text: friends) 

     //attributedString.addAttribute(NSLinkAttributeName, value: "checkIn", range: (string! as NSString).range(of: checkIn)) 
     //attributedString.addAttribute(NSLinkAttributeName, value: "tagFriends", range: (string! as NSString).range(of: friends)) 

     //postAddSetup.nameSurname.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.redIWorkOut(), NSFontAttributeName: UIFont.systemFont(ofSize: 13)] 

     //attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGray, range: (string! as NSString).range(of: checkIn)) 

     postAddSetup.nameSurname.attributedText = attributedString 


     print("atribute: \(attributedString)") 

    } 


func string1Action() { 
    print("action for string 1...") 
} 

func string2Action() { 
    print("action for string 2...") 
} 

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { 

    if URL.absoluteString == "string1" { 
     string1Action() 
    } else if URL.absoluteString == "string2" { 
     string2Action() 
    } 
    return false 
} 

extension NSMutableAttributedString { 
    func addLink(_ link: String, linkColor: UIColor, text: String) { 
     let pattern = "(\(text))" 
     let regex = try! NSRegularExpression(pattern: pattern, 
              options: NSRegularExpression.Options(rawValue: 0)) 
     let matchResults = regex.matches(in: self.string, 
             options: NSRegularExpression.MatchingOptions(rawValue: 0), 
             range: NSRange(location: 0, length: self.string.characters.count)) 

     for result in matchResults { 
      self.addAttribute(NSLinkAttributeName, value: link, range: result.rangeAt(0)) 
      self.addAttribute(NSForegroundColorAttributeName, value: linkColor, range: result.rangeAt(0)) 
     } 
    } 
} 

答えて

1

テキスト:

拡張子:

extension NSMutableAttributedString { 
    func addLink(_ link: String, linkColor: UIColor, text: String) { 
     let pattern = "(\(text))" 
     let regex = try! NSRegularExpression(pattern: pattern, 
               options: NSRegularExpression.Options(rawValue: 0)) 
     let matchResults = regex.matches(in: self.string, 
           options: NSRegularExpression.MatchingOptions(rawValue: 0), 
           range: NSRange(location: 0, length: self.string.characters.count)) 

     for result in matchResults { 
      self.addAttribute(NSLinkAttributeName, value: link, range: result.rangeAt(0)) 
      self.addAttribute(NSForegroundColorAttributeName, value: linkColor, range: result.rangeAt(0)) 
     } 
    } 
} 

編集:

は、この拡張機能を使用するカスタムUITextViewクラスを設定し、デリゲート関数shouldInteractWithのURLを使用して、それはUITextViewのハイパーリンクのロジックをシミュレートすることが可能です:

class CustomTextView: UITextView { 

    private let linksAttributes = [NSLinkAttributeName] 

    override func awakeFromNib() { 
     super.awakeFromNib() 

     let tapGest = UITapGestureRecognizer(target: self, action: #selector(self.onTapAction)) 
     self.addGestureRecognizer(tapGest) 
    } 

    @objc private func onTapAction(_ tapGest: UITapGestureRecognizer) { 
     let location = tapGest.location(in: self) 
     let charIndex = self.layoutManager.characterIndex(for: location, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) 

     if charIndex < self.textStorage.length { 
      var range = NSMakeRange(0, 0) 

      for linkAttribute in linksAttributes { 
       if let link = self.attributedText.attribute(linkAttribute, at: charIndex, effectiveRange: &range) as? String { 
        guard let url = URL(string: link) else { return } 
        _ = self.delegate?.textView?(self, shouldInteractWith: url, in: range, interaction: .invokeDefaultAction) 
       } 
      } 
     } 
    } 
} 
使用する方法

attributedString.addLink(yourLinkUrl, linkColor: yourLinkColor, text: yourLinkText) let textView = CustomTextView() textView.attributedText = attributedString

+0

こんにちはFrancesco。リンクを作成するための素晴らしい回避策。残念ながら、それは両方のリンクで同じ色を維持します。割り当てられた最後の色のみが使用されます。 –

+0

こんにちは@MarianPetrisorこれでlinkTextAttributesプロパティを使用する必要はありません、属性のテキストを設定します。 –

+0

私はlinkTextAttributesカラーとリンクを取り出し、このコードだけを残しました。これで、デフォルトの色が自動的に割り当てられます。リンクは機能しますが、右のテキストは見つかっていますが、割り当てられていない色は次のとおりです。 'attributedString.addLink(" string1 "、linkColor:UIColor.red、text:string1)' –

関連する問題