如何向 MKPointAnnotation 添加按钮?

2024-01-23

我刚刚在尝试向注释点添加详细信息按钮时陷入困境,不幸的是我不知道该怎么做。有人可以帮我吗?

The image below presents what I'd like to achieve. Thanks! enter image description here

MapKit 视图控制器:

import UIKit
import MapKit
import CoreLocation

class MapKitViewController: UIViewController, MKMapViewDelegate
{

let locationManager = CLLocationManager()

@IBOutlet weak var nmapView: MKMapView!
override func viewDidLoad()
{
    super.viewDidLoad()
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
    let location = CLLocationCoordinate2D(
        latitude: 53.4265107,
        longitude: 14.5520357)

    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegion(center: location, span: span)
    nmapView.setRegion(region, animated: true)
    nmapView.showsPointsOfInterest = false
    nmapView.showsUserLocation = true
    displayMarkers()
}

func displayMarkers() -> Void
{
    let jsonURL: NSURL = NSURL(string: "http://jsonstring.com/")!

    var dataFromNetwork: NSData = NSData(contentsOfURL: jsonURL)!
    let json = JSON(data: dataFromNetwork)
    var jsonSize = json.count

    var todaysDate:NSDate = NSDate()
    var dateFormatter:NSDateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    var formattedDate:String = dateFormatter.stringFromDate(todaysDate)

    let annotationView = MKAnnotationView()
    let detailButton: UIButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton
    annotationView.rightCalloutAccessoryView = detailButton


    for(var i = 0; i < jsonSize; i++)
    {
        if(json[i]["rozpoczecie"].stringValue == formattedDate)
        {
            let clubID = json[i]["id_klub"].stringValue
            let annotation = MKPointAnnotation()
            let (resultSet, err) = SD.executeQuery("SELECT * FROM Clubs WHERE ID = ?", withArgs: [clubID])
            if(err != nil){println("blad")}
            else
            {
                for row in resultSet
                {
                    let name = row["Name"]?.asString()
                    let latitude = row["Latitude"]?.asDouble()
                    let longitude = row["Longitude"]?.asDouble()
                    annotation.title = name
                    var markerLatitude: Double = latitude!
                    var markerLongitude: Double = longitude!
                    let location = CLLocationCoordinate2D(latitude: markerLatitude, longitude: markerLongitude)
                    annotation.setCoordinate(location)
                    annotation.subtitle = json[i]["nazwa"].stringValue
                }
                nmapView.addAnnotation(annotation)
            }
        }
    }
}

你做得对。你只需要实现这些方法来添加按钮以及标题和副标题

iOS 8 和 Xcode 6

 import UIKit
 import MapKit
 import CoreLocation

 class MapKitViewController: UIViewController, MKMapViewDelegate
 {
    let locationManager = CLLocationManager()
    @IBOutlet weak var nmapView: MKMapView!
    override func viewDidLoad()
    {
        super.viewDidLoad()
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        let location = CLLocationCoordinate2D(
            latitude: 53.4265107,
            longitude: 14.5520357)

        let span = MKCoordinateSpanMake(0.05, 0.05)
        let region = MKCoordinateRegion(center: location, span: span)
        nmapView.setRegion(region, animated: true)
        nmapView.showsPointsOfInterest = false
        nmapView.showsUserLocation = true
        displayMarkers()
    }

    // When user taps on the disclosure button you can perform a segue to navigate to another view controller
    func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
        if control == view.rightCalloutAccessoryView{
            println(view.annotation.title) // annotation's title
            println(view.annotation.subtitle) // annotation's subttitle

            //Perform a segue here to navigate to another viewcontroller
            // On tapping the disclosure button you will get here
        }
    }

    // Here we add disclosure button inside annotation window
    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {

        println("viewForannotation")
        if annotation is MKUserLocation {
            //return nil 
            return nil
        }

        let reuseId = "pin"
        var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView

        if pinView == nil {
            //println("Pinview was nil")
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            pinView!.canShowCallout = true
            pinView!.animatesDrop = true
            }

        var button = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton // button with info sign in it

        pinView?.rightCalloutAccessoryView = button


        return pinView
    }


    func displayMarkers() -> Void
    {
        let jsonURL: NSURL = NSURL(string: "http://atnight.wtznc.com/json.php")!

        var dataFromNetwork: NSData = NSData(contentsOfURL: jsonURL)!
        let json = JSON(data: dataFromNetwork)
        var jsonSize = json.count

        var todaysDate:NSDate = NSDate()
        var dateFormatter:NSDateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        var formattedDate:String = dateFormatter.stringFromDate(todaysDate)

        let annotationView = MKAnnotationView()

        // Adding button here wont do anything  so remove these two lines


        let detailButton: UIButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton
        annotationView.rightCalloutAccessoryView = detailButton

        // For adding button we have to use a method named as viewForAnnotation 

        for(var i = 0; i < jsonSize; i++)
        {
            if(json[i]["rozpoczecie"].stringValue == formattedDate)
            {
                let clubID = json[i]["id_klub"].stringValue
                let annotation = MKPointAnnotation()
                let (resultSet, err) = SD.executeQuery("SELECT * FROM Clubs WHERE ID = ?", withArgs: [clubID])
                if(err != nil){println("blad")}
                else
                {
                    for row in resultSet
                    {
                        let name = row["Name"]?.asString()
                        let latitude = row["Latitude"]?.asDouble()
                        let longitude = row["Longitude"]?.asDouble()
                        annotation.title = name
                        var markerLatitude: Double = latitude!
                        var markerLongitude: Double = longitude!
                        let location = CLLocationCoordinate2D(latitude: markerLatitude, longitude: markerLongitude)
                        annotation.setCoordinate(location)
                        annotation.subtitle = json[i]["nazwa"].stringValue
                    }
                    nmapView.addAnnotation(annotation)
                }
            }
        }
    }
}

看看我的输出。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向 MKPointAnnotation 添加按钮? 的相关文章

  • 无法在 Swift 中对闭包进行弱引用

    Update 我试着不弱化地写一下 好像也没有漏的情况 所以也许这个问题已经没有必要了 在 Objective C ARC 中 当你想让一个闭包能够在闭包内部使用它自己时 该块不能捕获对自身的强引用 否则它将是一个保留循环 因此您可以使闭包
  • ios swift parse:从 3 个类收集数据

    我有这样的结构 User CardSet 带有指向 User objectId 的指针 user 和 col name 带有点 cards 的卡片到 Card Set objectId 和列 name 我想选择所有卡数据 包括当前用户的卡集
  • dyld:无法加载插入的库

    当我尝试运行 UI 和单元测试时 出现异常 dyld 无法加载插入的库 private var containers Bundle Application AutoTestingApp app Frameworks IDEBundleInj
  • 从按钮执行 Segue 时应用程序冻结

    我的故事板中有一个按钮 它呈现一个带有模式序列的视图控制器 每次按下此按钮时 应用程序都会冻结 没有崩溃 也没有错误消息 prepareForSegue被调用 所有应该存在的视图控制器都在代码中prepareForSegue 但它们不会出现
  • 为什么 iOS 启动屏幕很慢?

    我的 iOS 应用程序启动屏幕大约需要 3 5 秒 我有一张将在启动屏幕后加载的地图 我的用户必须等待启动屏幕加载 然后再等待 3 秒才能加载地图 有没有办法最大限度地减少启动屏幕时间 基本上这种延迟意味着you在启动过程中做了一些非常错误
  • 使用未解析的标识符“FlurryAdInterstitial”

    我正在尝试整合Flurry Interstitial Ads使用cocoapods in Swift and Xcode 7 1 1 我正在关注开发人员雅虎网站上的此文档 https developer yahoo com flurry d
  • 如何让UITextView背景线与文字对齐?

    我正在尝试绘制 UITextView 的背景线 这是我用来画这些线的代码 CGContextBeginPath context CGContextSetStrokeColorWithColor context self horizontal
  • 会话重新启动后 AVcapture 会话启动缓慢

    我有一个主视图控制器 它连接到具有 avcapturesession 的第二个视图控制器 我第一次从主视图控制器转向捕获会话控制器 大约需要 50 毫秒 使用 仪器 检查 然后我从捕获会话返回到主视图控制器 然后从主控制器返回到 avcap
  • AVAssetExportSession 无法导出从 iCloud 下载的视频

    我正在尝试创建从用户相册中选择的视频的缩小版本 输出的最大尺寸为 720p 因此 在检索视频时 我使用 mediumQualityFormat as the deliveryMode 如果用户设备中不存在原始视频或其中等质量版本 这会导致
  • “预期的 ';'在 Swift 下的顶级声明符之后”

    我正在尝试将所有颜色设置在一个 Swift 文件中 该文件可以在我的整个应用程序中使用 下面的代码会导致 import Foundation import UIKit class DotColors let tsblueColor UICo
  • watchOS 错误:控制器接口描述中的未知属性

    我将 WKInterfacePicker 添加到情节提要中 并将其连接到界面控制器中的 IBOutlet 运行应用程序时 它在控制台中显示一条错误消息 控制器的接口描述 watchPicker 中的未知属性 Code interface I
  • UIPickerView selectRow 未按预期工作

    我创建了一个UIPickerView它有两个组件 第一个组件 A 的行数固定为 13 另一个组件 B 的行数可变 具体取决于 A 中选择的行 加载时UIPickerView我调用以下命令 以便我可以在两个组件中默认选择 但是我遇到的问题是只
  • UITableViewCell显示多种字体

    我想在 uitableviewcell 中以类似于 iPhone 地址簿的不同字体显示两个单词 例如 约翰Buchanan 您应该使用两个 UILable 或者您可以使用OH属性标签 https github com AliSoftware
  • Objective-C 中发送给对象的消息可以被监听或者打印出来吗? [复制]

    这个问题在这里已经有答案了 可能的重复 Objective C 中拦截方法调用 https stackoverflow com questions 1618474 intercept method call in objective c 如
  • 如何在 UICollectionView 中将行居中?

    我有一个UICollectionView与随机细胞 有什么方法可以让我将行居中吗 默认情况下它是这样的 x x x x x x x x x x x x x x 这是所需的布局 x x x x x x x x x x x x 我必须做这样的事
  • 在 Swift 中从 Parse 加载图像

    我成功地将数据从 Parse 提取到 swift 中 但我的图像似乎没有按照我的方式工作 在我的 cellForRowAtIndexPath 方法中 我执行以下操作 var event AnyObject eventContainerArr
  • 处理 UICollectionView 中的点击手势

    由于我无法使用任何框架来创建相册 因此我尝试使用 Collection View 创建自己的相册 但我一开始就陷入困境 我的目标是将网络服务中的所有图像显示到我的集合视图中 因为所有图像都已显示 下一步是当有人点击任何单元格时 我可以在新视
  • iPhone 上的纵向 UISplitViewController 在 iOS 8 中始终显示主视图和细节视图

    UISplitViewController in portrait在 iPhone 上始终显示主控和细节iOS 8 我尝试子类化UISplitViewController并将其配置为同时显示主视图和细节视图 但没有任何效果 class AP
  • 是否可以跨 2 个不同的 iOS 应用程序访问数据?

    假设我在 App1 中存储了一些 ID 数据 并希望在同一设备上的 App2 中访问它 平台上可以这样吗 如果没有的话有什么解决方法吗 您可以使用iOS 钥匙扣 http developer apple com library ios do
  • 像 TraceGL 一样分析 Objective C 中的代码路径?

    TraceGL 是一个非常简洁的项目 它允许 JS 程序员跟踪 Javascript 中的代码路径 它看起来像这样 我想为 Objective C 构建类似的东西 我知道运行时使跟踪方法调用变得相当容易 但是我如何跟踪控制流 例如 在上面的

随机推荐

  • C# 检查复选框状态的更清晰方法?

    我有以下代码 它将布尔值列表作为参数 然后通过单独验证列表来设置每个检查列表的检查状态 有没有更有效的方法来编写以下代码 例如 通过使用循环 public PointCtrlRowSelectionForm List
  • 将函数应用于 R 中的数据帧列表

    我需要有关如何以迭代方式管理列表的帮助 我有以下清单list它由多个具有相同列但行数不同的数据框组成 例子 1 id InpatientDays ERVisits OfficeVisits Narcotics 1 a 0 0 18 1 2
  • 使用 .aar NoClassDefFoundError 但类存在并且已 Dexed

    我有几个项目是为了创建 aar 而构建的 然后我将此 aar 导入到 Android Studio 的 libs 下 此依赖项的 build gradle 文件如下所示 repositories flatDir dirs libs depe
  • 我如何将 ╚ 放入批处理文件中

    我正在尝试在批处理文件中添加行 等 但是将它们直接插入批处理文件中会产生一些我没有输入的奇怪字符 我正在使用记事本 通过alt 200键入这些字符或者取决于我想要的字符 Windows 10 和命令提示符版本 10 0 10240 有什么解
  • 如何在node.js中使用基本身份验证从url获取用户名和密码? [复制]

    这个问题在这里已经有答案了 我需要获取浏览器从 url 发送到我的 node js 应用程序的用户名和密码 我挖掘了各种文档和对象 但找不到任何有用的东西 有人知道该怎么做吗 使用身份验证标头不是一个选项 因为现代的 Bowser 不设置它
  • 是否可以像IPC一样使用Mac OS X XPC在进程之间交换消息?如何?

    据 Apple 介绍 Lion 中引入的新 XPC Services API 为与 Grand Central Dispatch GCD 和 launchd 集成的基本进程间通信提供了一种轻量级机制 似乎可以使用这个 API 作为一种 IP
  • UIWebView 最初不加载某些 URL

    UIWebView 遇到如此奇怪的问题 我无法在网上找到解决方案 我有一个 iPad 应用程序 其中有网络视图 首次安装并运行应用程序时 我尝试加载一个教育网站 http my tac edu au 网络视图只是挂起并超时 我杀死了该应用程
  • 使用相同的内部表示和最少的样板处理多种类型?

    我发现自己在用 Haskell 编写大型程序时经常遇到一个问题 我发现自己经常想要多个不同的类型共享内部表示和几个核心操作 有两种相对明显的方法可以解决这个问题 一种是使用类型类 GeneralizedNewtypeDeriving扩大 将
  • SOAP 和 HTTP 协议的区别?

    SOAP 和 HTTP 协议有什么区别 当我们说 SOAP over HTTP 时 这是什么意思 您可以通过 HTTP 提供任何内容 例如 HTML 图像 声音 视频等 SOAP 是一种基于 XML 的消息编码 通常通过 HTTP 发送 但
  • 如何将比其父元素宽的元素居中?

    我目前有一个固定宽度为 900px 的 div 我想添加一个固定宽度为 950px 的子 iframe 并且我希望它与中心完美对齐 那怎么办呢 Thanks 您可以将子项放置在 50 处 然后使用负边距 即子项宽度的一半 parent po
  • 检查 php 脚本是否仍在运行

    我有一个脚本可以监听 jabber 服务器并做出相应的响应 虽然它不应该停止 但昨晚它却停止了 现在我想每分钟运行一个 cron 作业来检查脚本是否正在运行 如果没有运行则启动它 问题是 如何检查特定脚本是否仍在运行 一些解决方案已经发布h
  • C# 替换 docx 中的文本字符串

    使用 C 有没有一种好方法可以在 docx 文件中查找和替换文本字符串 而无需在该计算机上安装 word 是的 使用Open XML http openxmldeveloper org default aspx 这是一篇解决您的具体问题的文
  • 以 table.column 格式返回 Oracle 列名?

    是否有任何设置或方法可以用来让 Oracle 返回结果 table table
  • 如何使用Vite从公共目录导入JSON文件?

    我有一个 Vue3 Vite 项目 其中一些数据必须从外部 JSON file 但是当我构建项目时 JSON 文件被捆绑 我需要将 JSON 文件保留在外部 我尝试过的 第一次尝试vite config ts export default
  • 从高级编辑器更改数据类型与数据转换

    我正在使用 SSIS 创建一些包 我对周围感到困惑数据转换变换组件并从高级编辑器更改列数据类型 如果我可以进入高级编辑器并更改输出的数据类型 为什么我需要输入数据转换 这只是取决于偏好还是使用两种方法之间有区别吗 在展示两种方法之间的差异之
  • 附加文件时的 Rails ActiveStorage 范围

    使用 ActiveStorage 时 如何创建附加文件的范围 例如 class Check lt ActiveRecord Base has one attached image end 我想要类似的东西Check has attached
  • angularJS element.on 回调和作用域.$apply

    在此示例中 我有一个带有附加指令的输入 该指令旨在在输入旁边显示消息 还有另一个输入和一个用于添加消息的按钮 显示一些消息后 关注带有附加指令的输入应该会清除消息 http jsfiddle net viro WBqxf http jsfi
  • 使用 PHP 创建目录中所有类的实例

    我有一个包含多个 PHP 文件的目录 这些文件由与文件同名的类组成 Sample php的班级将被称为Sample 每个类都有一个名为的函数OnCall 如何在我的目录中创建每个类的实例并执行它们的所有OnCall s 我无法手动完成 sa
  • 为什么 ASP.NET Core 本地化不起作用

    我创建了一个空项目 启动 cs public void ConfigureServices IServiceCollection services services AddLocalization s gt s ResourcesPath
  • 如何向 MKPointAnnotation 添加按钮?

    我刚刚在尝试向注释点添加详细信息按钮时陷入困境 不幸的是我不知道该怎么做 有人可以帮我吗 The image below presents what I d like to achieve Thanks MapKit 视图控制器 impor