I have textfield and i want to getting some text clickable. Below is my code please review and thanks.
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
If you want your UITextView
detect link, phoneNumber, address, calendarEvent or simply detect all types than use 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]
textVw
is a object of UITextView
as
@IBOutlet var textVw: UITextView!
You can also make text detectable from storyboard as below screenshot.
You can use this code to make your UITextField
clickable and open a URL for example
// 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)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.