Swift 4/Google Maps崩溃求助:NSInvalidArgumentException异常
-[UIView setDelegate:]: unrecognized selector Hey there, let's break down this crash you're hitting—it's a super common gotcha when setting up Google Maps in iOS projects, and I bet we can fix it quickly.
What's Actually Happening?
The error -[UIView setDelegate:]: unrecognized selector sent to instance tells us one clear thing: you're trying to set a delegate on a plain old UIView, but UIView doesn't have a delegate property. Only GMSMapView (the Google Maps view class) does. So somewhere in your setup, a UIView is being treated like a GMSMapView.
Step-by-Step Fixes
Let's go through the most likely culprits:
Check your Storyboard/XIB view class
Open your MapViewController's Storyboard or XIB, find the view you want to use as the map. Then:- Select the view, open the Identity Inspector (right panel, third icon).
- In the Class field, make sure it's set to
GMSMapView(not the defaultUIView). - Double-check the Module field—set it to your project's module or choose
Inherit from Targetto avoid class mismatches.
Fix your code's view declaration
Head to your MapViewController code and look for the IBOutlet or code-created map view. If it's declared asUIView, that's the problem:// ❌ Wrong: This is a plain UIView, no delegate property @IBOutlet weak var mapView: UIView! // ✅ Correct: Declare it as GMSMapView @IBOutlet weak var mapView: GMSMapView!If you're creating the map programmatically, make sure you're initializing
GMSMapView, notUIView:// ❌ Wrong let mapView = UIView(frame: view.bounds) // ✅ Correct let mapView = GMSMapView(frame: view.bounds)Verify your delegate setup timing
Make sure you're setting the delegate after the map view is fully loaded. The safest place isviewDidLoad():override func viewDidLoad() { super.viewDidLoad() // Only set delegate once the map view exists mapView.delegate = self // Add your other map config here (camera position, markers, etc.) }Double-check IBOutlet connections
Sometimes IBOutlets get connected to the wrong view (since you have three UIViews in your controller). Right-click themapViewIBOutlet in your code—you'll see which view it's linked to. Confirm it's the one you intended to use as the Google Map.
Bonus: Clean Project Cache
If none of the above works, try cleaning your Xcode project (press Cmd + Shift + K) and rebuilding. Xcode's cache can sometimes hold onto old class references that cause weird issues like this.
内容的提问来源于stack exchange,提问作者Bruce Bookman

