我是 swift 编程的新手,我正在尝试构建一个在 map 上显示一些图钉的应用程序。当用户单击图钉时,会出现一个带有按钮的注释。如果单击该按钮,它将在 Safari 中打开一个 url。
按照一些教程,我设法拥有一个带有图钉和按钮的功能性应用程序,但我无法打开 URL。
这是我用来构建应用程序的代码:
struct WebCam {
var name: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
var url: String
}
class FirstViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
let webcams = [WebCam(name: "WH1", latitude: 51.5549, longitude: -0.108436, url: "www.test.it"),
WebCam(name: "WH2", latitude: 51.4816, longitude: -0.191034, url: "www.google.it")]
func fetchWebcamsOnMap(_ webcams: [WebCam]) {
for webcam in webcams {
let annotations = MKPointAnnotation()
annotations.title = webcam.name
annotations.coordinate = CLLocationCoordinate2D(latitude: webcam.latitude, longitude: webcam.longitude)
mapView.addAnnotation(annotations)
}
}
extension FirstViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotations: MKAnnotation) ->
MKAnnotationView? {
let identifier = "WebCam"
var view: MKMarkerAnnotationView
// 4
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKMarkerAnnotationView {
dequeuedView.annotation = annotations
view = dequeuedView
} else {
// 5
view = MKMarkerAnnotationView(annotation: annotations, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
let mapsButton = UIButton(frame: CGRect(origin: CGPoint.zero,
size: CGSize(width: 30, height: 30)))
mapsButton.setBackgroundImage(UIImage(named: "webcam"), for: UIControl.State())
view.rightCalloutAccessoryView = mapsButton
}
return view
}
这是检索 UIButton 按下的代码
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
}
}
我尝试通过访问它来使用所选网络摄像头的 URL 进行简单的控制台打印
let web = view.annotation as! WebCam
let webURL = WebCam.url
但是显示错误。
最佳答案
WebCam
必须是 MKPointAnnotation
的子类
class WebCam : MKPointAnnotation {
var url : String
init(name : String, latitude : CLLocationDegrees, longitude : CLLocationDegrees, url : String) {
self.url = url
super.init()
self.title = name
self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
然后你可以创建实例
let webcams = [WebCam(name: "WH1", latitude: 51.5549, longitude: -0.108436, url: "www.test.it"),
WebCam(name: "WH2", latitude: 51.4816, longitude: -0.191034, url: "www.google.it")]
fetchWebcamsOnMap
可以简化为
func fetchWebcamsOnMap(_ webcams: [WebCam]) {
mapView.addAnnotations(webcams)
}
和
let web = view.annotation as! WebCam
let webURL = web.url
会起作用。
关于ios - 从 xcode 中的注释映射访问结构参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58727066/