How can I create a “hyperlink” with Swift?

前端 未结 3 797
伪装坚强ぢ
伪装坚强ぢ 2021-01-07 03:53

I\'m trying to make separate pieces of text UILabels clickable. What I\'m looking for is commonly known as a hyperlink in web development.



        
3条回答
  •  心在旅途
    2021-01-07 04:33

    Swift 3 I created a LinkUILabel class in github: https://github.com/jorgecsan/LinkUILabel With this you only need add the url inspectable as the shows the image: or assign the url variable programmatically:

    linkUILabel.url = "www.example.com"
    

    If you want to implement by your self also I found that solution!:)

    using:

    // This is the label
    @IBOutlet weak var label: UILabel!
    
    override func loadView() {
        super.loadView()
    
        // This is the key
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.onClicLabel(sender:)))
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(tap)
    }
    
    // And that's the function :)
    func onClicLabel(sender:UITapGestureRecognizer) {
        openUrl("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)
        }
    }
    

    Hope it helps!:)

提交回复
热议问题