2015-07-16 20 views
5

Sono nuovo allo sviluppo iOS.sottolineano parte di uiLabel e collegamento sottolineato sezione

Ho un'etichetta LatestInfo questo ha un testo e ha lo scopo di avere un collegamento a un sito Web: ad es. For the latest information visit example.com/latestInfo

Desidero che il display sottolinei l'url example.com/latestInfo e lo renda cliccabile.

Sto usando Swift non Obejective-C

Come posso fare per fare questo?

EDIT secondo la richiesta di Pierre:

@IBOutlet weak var linkLabel: UITextView! 
let string    = "A great link : Google" 
let range    = (string as NSString).rangeOfString("Google") 
let attributedString = NSMutableAttributedString(string: string) 

attributedString.addAttribute(NSLinkAttributeName, value: NSURL("http://www.google.fr")!, range: range) 
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(int: 1), range: range) 
attributedString.addAttribute(NSUnderlineColorAttributeName, value: UIColor.orangeColor(), range: range) 

linkLabel.attributedText = attributedString 
+0

un'occhiata a questo [SO] (http://stackoverflow.com/questions/28053334/how-to-underline- a-uilabel-in-swift) link – Akhilrajtr

risposta

12

Cercare NSMutableAttributedString e soprattutto per NSLinkAttributeName. Ci sono un sacco di tutorial e domande StackOverflow su questo. Puoi anche leggere la documentazione di Apple sulla stringa attribuita TextView è l'unico componente in grado di aprire i collegamenti. Quindi, basta sostituire l'etichetta con quello e:

let string    = "A great link : Google" 
let range    = (string as NSString).rangeOfString("Google") 
let attributedString = NSMutableAttributedString(string: string) 

attributedString.addAttribute(NSLinkAttributeName, value: NSURL("http://www.google.fr")!, range: range) 
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(int: 1), range: range) 
attributedString.addAttribute(NSUnderlineColorAttributeName, value: UIColor.orangeColor(), range: range) 


textView.attributedText = attributedString 
+0

Sono riuscito a sottolineare il testo. Come posso rendere cliccabile questa sezione di testo? – Pindo

+0

Ho modificato la mia risposta. È quello che vuoi? – Pierre

+0

Questo lo rende un collegamento. Mi piacerebbe che questo link fosse aperto in safari – Pindo

1

enter image description here

Please create one UILabel & check it's properties. 
Please select Text on first changed it's to plain to Attributed. 

    Now you can seen you label text in one Textfield. select that text & right click to you mouse & goto Font menu. you can seen Underline. select it. you can seen underline in your Label.