在Xcode中添加地图标注及代码报错问题求助
Hey there! Let's tackle those two errors you're seeing in your Xcode map code—they're straightforward fixes once you know what's going on.
Error 1: 'MKPointAnnotation' has no member 'setCoordinate'
In iOS, MKPointAnnotation uses a stored property coordinate instead of a setCoordinate() method to set its location. The method you're trying to use comes from older Objective-C patterns, but Swift uses direct property assignment here.
Instead of:
point1.setCoordinate(WCAula)
You should write:
point1.coordinate = WCAula
Error 2: Use of unresolved identifier 'map'
Swift is case-sensitive! You declared your map view outlet with a capital M (@IBOutlet var Map: MKMapView!), but you're trying to access it with a lowercase m (map.addAnnotation(point1)). Most iOS developers use lowercase for variable names to follow Swift conventions, so adjusting the outlet name to match your usage is the way to go.
Corrected Full Code
Here's your code with both fixes applied, plus a small tweak to use modern Swift syntax for CLLocationCoordinate2D:
import UIKit import MapKit import CoreLocation class ViewController: UIViewController { // Renamed to lowercase 'map' to match usage and follow conventions @IBOutlet var map: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Modern Swift initializer instead of CLLocationCoordinate2DMake let WCAula = CLLocationCoordinate2D(latitude: 50.3044, longitude: 4.5724) let point1 = MKPointAnnotation() point1.coordinate = WCAula // Fixed property assignment point1.title = "WCAula" map.addAnnotation(point1) // Now matches the outlet name } }
Quick Checks
- Don't forget to re-connect your storyboard/xib's map view to the renamed
mapoutlet if needed. - Using
letinstead ofvarfor variables that don't change (likeWCAulaandpoint1) makes your code safer and more readable.
内容的提问来源于stack exchange,提问作者Rick

