如何在swift iOS中编写正确的目标选择器?

时间:2016-06-07 16:13:45

标签: ios google-maps uibutton swift2 xcode7

所以我有这个按钮使用谷歌地图给出方向,问题是我不知道如何在UIButton中编写适当的目标选择器,因为最新的swift

这是我的按钮:

directionButton.addTarget(self, action: #selector(ViewController.goToMap(String(format: "%.6f", place.coordinate.latitude), longitude: String(format: "%.6f", place.coordinate.longitude))), forControlEvents: UIControlEvents.TouchUpInside)

这是我的功能:

func goToMap(latitude: String, longitude: String) {
        print("function gotoMap works!!!!")
        if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
            UIApplication.sharedApplication().openURL(NSURL(string:
                "comgooglemaps://?saddr=&daddr=\(latitude),\(longitude)&directionsmode=driving")!)
        } else {
            print("Can't use comgooglemaps://")

            var addressToLinkTo = ""

            addressToLinkTo = "http://?saddr=&daddr=\(latitude),\(longitude)&directionsmode=driving"

            addressToLinkTo = addressToLinkTo.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

            let url = NSURL(string: addressToLinkTo)
            UIApplication.sharedApplication().openURL(url!)
        }

}

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

您无法通过selector传递参数,将您的方法修改为goToMap()并存储纬度&要在函数中使用的实例变量中的经度数据。然后你可以使用

directionButton.addTarget(self, action: #selector(ViewController.goToMap()))

func goToMap(){
 // use value stored in instance var
 // self.latitude
 // self.longitude
}