2017-08-09 680 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) 
    } 
}