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

时间:2018-02-07 17:29:11

标签: ios swift uibutton iboutlet

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

UIButton

无论如何,我的应用程序有多个按钮(错误:这里我没有原始感知标签和按钮之间的差异):

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

每个都要打开一个相应的URL:

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

1 个答案:

答案 0 :(得分:0)

首先你应该更好地使用按钮来处理这些事情(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")
  }
}