简体   繁体   English

UITextView与Swift中的超链接文本

[英]UITextView with hyperlink text in Swift

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 . 如果您希望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]

textVw is a object of UITextView as textVwUITextView的对象,如

@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 您可以使用此代码使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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM