我需要在我的应用程序中动态地向 labels
添加点击功能(以打开网站),我想在 class
中创建静态函数。我想在我的应用程序的任何 ViewController
中启动该功能。
我使用 Swift 3 完成了这个:
class Launcher {
static func openWeb(label: UILabel, url: String) {
func tapFunction(sender:UITapGestureRecognizer) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URL(string: url)!)
}
}
let tap = UITapGestureRecognizer(target: self, action: #selector(tapFunction))
label.isUserInteractionEnabled = true
label.addGestureRecognizer(tap)
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URL(string: url)!)
}
}
}
但不起作用,因为我在 action: #selector(tapFunction)
错误:“#selector”的参数不能引用本地函数“tapFunction(sender:)”
如果我使用 action: #selector(myView.tapFunction)
在 ViewController
代码中使用它,如下所示,有效
viewDidLoad
内部
let tap = UITapGestureRecognizer(target: self, action: #selector(MyViewController.tapFunction))
mylabel.isUserInteractionEnabled = true
mylabel.addGestureRecognizer(tap)
ViewController
中的分离函数
func tapFunction(sender:UITapGestureRecognizer) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URL(string: url)!)
}
}
我想将这最后一段代码转换为我的 Class
中的静态函数,以便在任何 ViewController
中调用它。谢谢
最佳答案
Try resolve it using extension
extension UILabel {
func openWeb(url: String) {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapFunction))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tap)
openURL(url: url)
}
func tapFunction(sender:UITapGestureRecognizer) {
openURL(url: "")
}
func openURL(url: String) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URL(string: url)!)
}
}
}
let label = UILabel()
label.openWeb(url: "123")
To store link into label you can use associations with label object.
关于ios - 如何在静态函数中使用 UITapGestureRecognizer 向标签添加点击功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45621839/