2016-08-30 33 views
12

z nieedytowalnego UITextView, chciałbym umieścić tekst jak to w iOS9 +:UITextView z tekstu hiperłącza

Wystarczy click here zarejestrować

mogę utworzyć funkcję i manipulować tekstu ale czy jest prostszy sposób?

widzę, że mogę używać NSTextCheckingTypeLink więc coraz klikalny tekst bez części „kliknij tutaj” jest prosty w konstruktorze Interface:

Wystarczy http://example.com zarejestrować

Używam Xcode 8 i Swift 3, jeśli jest to istotne.

Odpowiedz

17

Ustaw kontroler widoku w celu dostosowania do UITextViewDelegate i następujący kod:

override func viewDidLoad() { 
    super.viewDidLoad() 

    // You must set the formatting of the link manually 
    let linkAttributes = [ 
     NSLinkAttributeName: NSURL(string: "https://www.apple.com")!, 
     NSForegroundColorAttributeName: UIColor.blue 
    ] as [String : Any] 

    let attributedString = NSMutableAttributedString(string: "Just click here to register") 

    // Set the 'click here' substring to be the link 
    attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10)) 

    self.textView.delegate = self 
    self.textView.attributedText = attributedString 
} 

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { 
    return true 
} 
+0

UITextItemInteraction jest iOS10 +, ale potrzebuję iOS9 +. Zobaczę, czy mogę to naprawić i zagłosować na chwilę. –

+1

W swift 4 atrybuty zostały zmienione z NSLinkAttributedName na .link i NSForegroundColorAttributeName na .foregroundColor –

0

chciałem zrobić to samo, co skończyło się tylko za pomocą UIButton tytułem „kliknij tutaj” otoczony UILabels " wystarczy "i", aby się zarejestrować, a następnie:

@IBAction func btnJustClickHereLink(_ sender: UIButton) { 
    if let url = URL(string: "http://example.com") { 
     UIApplication.shared.openURL(url) 
    } 
}