You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中Annotation的Button点击传值问题:无法读取注解属性

Fix: "Type 'MapController' has no member 'TaskDetail' When Accessing Annotation Properties"

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

  1. Cast the sender to your Annotation subclass
    In your button tap handler, the default sender type is UIButton?. You need to safely cast it to your Annotation class 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
        }
    
  2. Access the Annotation's properties directly
    Once you have the correct Annotation instance, you can access its TaskDetail property (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.
    }
    
  3. Double-check your Annotation class definition
    Make sure your Annotation class actually declares the TaskDetail property (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:34:12