如何让 UILabel 点击像 UIButton 一样打开 URL

How to have UILabel tap act like a UIButton to open URL

这是我问的第一个编程问题,没有意识到 UILabelsUIButtons 之间的差异,关于最基本的应用程序操作之一。当然,评论中明显的答案是只使用 UIButtons。但是,如果有人可以使用 Sh_Khan 和编辑的巧妙代码使 UILabelUIButton 一样工作,而不是删除这个已回答的问题,那就是:

// 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)
    }
}

无论如何,我的应用程序有多个按钮(错误:这是我最初没有察觉到标签和按钮之间差异的地方):

 @IBOutlet weak var labelONE: UILabel!
 @IBOutlet weak var labelTWO: UILabel!
 @IBOutlet weak var labelTHREE: UILabel!

其中每一个都是开单对应URL:

openUrl("https://www.google.com")
openUrl("https://www.yahoo.com")
openUrl("https://www.twitter.com")

首先你最好使用按钮来处理类似的事情 (UIButton) 而不是标签 (UILabel) 来解决你的问题试试这个

 // This is the key
let tap = UITapGestureRecognizer(target: self, action: #selector(self.onClicLabel(sender:)))
label.isUserInteractionEnabled = true
label.addGestureRecognizer(tap)

let tap2 = UITapGestureRecognizer(target: self, action: #selector(self.onClicLabel(sender:)))
label2.isUserInteractionEnabled = true
label2.addGestureRecognizer(tap2)

@objc func onClicLabel(sender:UITapGestureRecognizer) {
  if(sender.view == self.label)
  {
     openUrl("http://www.google.com")
  }
  else if(sender.view == self.label2)
  {
     openUrl("http://www.twitter.com")
  }
}