2017-08-09 355 views
0

我有文本框,我想獲取一些可點擊的文本。以下是我的代碼請審查和感謝。在Swift中使用超鏈接文本的UITextView

let string = "Google" 
let linkString = NSMutableAttributedString(string: string) 
linkString.addAttribute(NSLinkAttributeName, value: NSURL(string: "https://www.google.com")!, range: NSMakeRange(0, string.characters.count)) 
linkString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 25.0)!, range: NSMakeRange(0, string.characters.count)) 
textView.attributedText = linkString 
textView.selectable = true 
textView.userInteractionEnabled = true 
+0

使用的TextView爲你的概念,而不是文本框的 –

回答

1

如果你希望你UITextView檢測鏈路,phoneNumber的,地址,calendarEvent或簡單地檢測所有類型不是使用UIDataDetectorTypes

let yourstring = "Check Google search. www.google.com" 

// Update UITextView font and font size. 
textVw.font = UIFont(name: "HelveticaNeue", size: 25) 

// Make web links clickable 
textVw.isUserInteractionEnabled = true 
textVw.isSelectable = true 
textVw.isEditable = false 
textVw.dataDetectorTypes = UIDataDetectorTypes.link 

// Update UITextView content 
textVw.text = yourstring 

// Update hyperlink text colour. 
textVw.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.blue, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleNone.rawValue] 

textVwUITextView作爲

@IBOutlet var textVw: UITextView! 

您也可以使文本也可以偵測到故事板作爲下面的截圖一個對象。 Attribute inspector

0

您可以使用此代碼來使你的UITextField點擊並打開一個URL,例如

// This is the label 
    @IBOutlet weak var label: UILabel! 

override func loadView() { 
    super.loadView() 

    // here is where you make your label clickable 
    let tap = UITapGestureRecognizer(target: self, action: #selector(self.onClicLabel(sender:))) 
    label.isUserInteractionEnabled = true 
    label.addGestureRecognizer(tap) 
} 

// And here are the functions to open a URL 
func onClicLabel(sender:UITapGestureRecognizer) { 
    openUrl(urlString: "http://www.google.com") 
} 


func openUrl(urlString:String!) { 
    let url = URL(string: urlString)! 
    if #available(iOS 10.0, *) { 
     UIApplication.shared.open(url, options: [:], completionHandler: nil) 
    } else { 
     UIApplication.shared.openURL(url) 
    } 
}