2015-06-24 10 views
5

io uso questo codice:UITextView open link alla spina

var textView = UITextView(x: 10, y: 10, width: CardWidth - 20, height: placeholderHeight) //This is my custom initializer 
textView.text = "dsfadsaf www.google.com" 
textView.selectable = true 
textView.dataDetectorTypes = UIDataDetectorTypes.Link 
textView.delegate = self 
addSubview(textView) 

Il problema è il collegamento necessita lunga gesto rubinetto da aprire. Voglio che si apra con un solo tocco, proprio come nell'app Facebook.

+0

[Questa risposta] (http://stackoverflow.com/a/26495954/1033565) di Benjamin Bojko potrebbe aiutarti. – paolo

+1

FYI - È anche possibile [creare collegamenti intercettabili in UILabel] (http://stackoverflow.com/a/29352519/168594). (Nel caso in cui stavi usando un UITextView solo per i rivelatori di dati.) – zekel

risposta

6

L'esempio che segue funziona solo su iOS 8+

Tap riconoscitore:

let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("tappedTextView:")) 
myTextView.addGestureRecognizer(tapRecognizer) 
myTextView.selectable = true 

richiamata:

func tappedTextView(tapGesture: UIGestureRecognizer) { 

    let textView = tapGesture.view as! UITextView 
    let tapLocation = tapGesture.locationInView(textView) 
    let textPosition = textView.closestPositionToPoint(tapLocation) 
    let attr: NSDictionary = textView.textStylingAtPosition(textPosition, inDirection: UITextStorageDirection.Forward) 

    if let url: NSURL = attr[NSLinkAttributeName] as? NSURL { 
     UIApplication.sharedApplication().openURL(url) 
    } 

} 

Swift 3 e nessuna forza scarta:

func tappedTextView(tapGesture: UIGestureRecognizer) { 
     guard let textView = tapGesture.view as? UITextView else { return } 
     guard let position = textView.closestPosition(to: tapGesture.location(in: textView)) else { return } 
     if let url = textView.textStyling(at: position, in: .forward)?[NSLinkAttributeName] as? URL { 
      UIApplication.shared.open(url) 
     } 
    } 
+0

Impossibile usare la chiave 'NSLinkAttributeName' in Swift 4. Una soluzione semplice è usare invece la chiave' "NSLink" '. – Legonaftik