Swift 4中Annotation的Button点击传值问题:无法读取注解属性
Hey there, let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
Your Annotation class is a subclass of UIButton, which means when you tap the button, the sender in your tap handler is an instance of Annotation—but right now, you're mistakenly trying to access a TaskDetail property on your MapController instead of on the actual Annotation button that was tapped. That's why the compiler is yelling that MapController has no such member.
Step-by-Step Solution
Cast the sender to your Annotation subclass
In your button tap handler, the default sender type isUIButton?. You need to safely cast it to yourAnnotationclass to access its properties:@objc func onAnnotationTapped(_ sender: UIButton) { // Safely unwrap and cast the sender to Annotation guard let tappedAnnotation = sender as? Annotation else { print("Could not cast sender to Annotation type") return }Access the Annotation's properties directly
Once you have the correctAnnotationinstance, you can access itsTaskDetailproperty (or any other properties you've defined) directly on that instance:// Now access TaskDetail from the tapped Annotation let taskDetail = tappedAnnotation.TaskDetail // Do whatever you need with taskDetail here—display it, pass it to another view, etc. }Double-check your Annotation class definition
Make sure yourAnnotationclass actually declares theTaskDetailproperty (typos happen!):class Annotation: UIButton { // Replace with your actual property type (String, custom model, etc.) var TaskDetail: String? // Your initializer and other class logic here }
Why This Works
By casting the sender to Annotation, you're telling the compiler "this button is actually my custom Annotation subclass, so it has the properties I defined." Before, you were trying to pull TaskDetail from the wrong object (your MapController), which doesn't have that property—hence the error.
内容的提问来源于stack exchange,提问作者gorp88

