├── .gitignore ├── .swiftlint.yml ├── README.md ├── SwiftMapViewCustomCallout.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist └── xcuserdata │ └── rryan.xcuserdatad │ └── xcschemes │ ├── SwiftMapViewCustomCallout.xcscheme │ └── xcschememanagement.plist └── SwiftMapViewCustomCallout ├── AppDelegate.swift ├── Base.lproj ├── LaunchScreen.xib └── Main.storyboard ├── CalloutView.swift ├── CustomAnnotationView.swift ├── ExampleCalloutView.swift ├── Images.xcassets └── AppIcon.appiconset │ └── Contents.json ├── Info.plist └── ViewController.swift /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## User settings 6 | xcuserdata/ 7 | 8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 9 | *.xcscmblueprint 10 | *.xccheckout 11 | 12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 13 | build/ 14 | DerivedData/ 15 | *.moved-aside 16 | *.pbxuser 17 | !default.pbxuser 18 | *.mode1v3 19 | !default.mode1v3 20 | *.mode2v3 21 | !default.mode2v3 22 | *.perspectivev3 23 | !default.perspectivev3 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | 28 | ## App packaging 29 | *.ipa 30 | *.dSYM.zip 31 | *.dSYM 32 | 33 | ## Playgrounds 34 | timeline.xctimeline 35 | playground.xcworkspace 36 | 37 | # Swift Package Manager 38 | # 39 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 40 | # Packages/ 41 | # Package.pins 42 | # Package.resolved 43 | # *.xcodeproj 44 | # 45 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 46 | # hence it is not needed unless you have added a package configuration file to your project 47 | # .swiftpm 48 | 49 | .build/ 50 | 51 | # CocoaPods 52 | # 53 | # We recommend against adding the Pods directory to your .gitignore. However 54 | # you should judge for yourself, the pros and cons are mentioned at: 55 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 56 | # 57 | # Pods/ 58 | # 59 | # Add this line if you want to avoid checking in source code from the Xcode workspace 60 | # *.xcworkspace 61 | 62 | # Carthage 63 | # 64 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 65 | # Carthage/Checkouts 66 | 67 | Carthage/Build/ 68 | 69 | # Accio dependency management 70 | Dependencies/ 71 | .accio/ 72 | 73 | # fastlane 74 | # 75 | # It is recommended to not store the screenshots in the git repo. 76 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 77 | # For more information about the recommended setup visit: 78 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 79 | 80 | fastlane/report.xml 81 | fastlane/Preview.html 82 | fastlane/screenshots/**/*.png 83 | fastlane/test_output 84 | 85 | # Code Injection 86 | # 87 | # After new code Injection tools there's a generated folder /iOSInjectionProject 88 | # https://github.com/johnno1962/injectionforxcode 89 | 90 | iOSInjectionProject/ 91 | -------------------------------------------------------------------------------- /.swiftlint.yml: -------------------------------------------------------------------------------- 1 | disabled_rules: 2 | - force_cast 3 | - discarded_notification_center_observer 4 | - type_body_length 5 | - weak_computed_property 6 | 7 | opt_in_rules: 8 | - empty_string 9 | 10 | file_length: 11 | warning: 500 12 | error: 1200 13 | 14 | line_length: 15 | warning: 300 16 | error: 400 17 | 18 | included: 19 | 20 | excluded: 21 | - Carthage 22 | - Pods 23 | 24 | identifier_name: 25 | excluded: 26 | - id 27 | - i 28 | - j 29 | - k 30 | - url 31 | - db 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Custom MapView Annotation Callouts in Swift 2 | 3 | This is an demonstration of a custom map view annotation callouts in Swift. 4 | 5 | The easiest way to customize callouts is to implement the `leftAccessoryView` and `rightAccessoryView`. If you want more considerable changes for what appears below the title in the callout (e.g. add some custom imagery or whatever), you can also implement the `detailAccessoryView`. 6 | 7 | But sometimes, even that is insufficient. For example, if you want to change the background color of the callout, or change the shape of the callout bubble, or whatever, adjusting the various accessory views is insufficient. In those cases, you can disable the standard the MapKit callout, and generate your own. You simply have to identify when the callout is selected, and then add a subview to the annotation view. 8 | 9 | When you go down this road, though, you're signing up for the manual rendering of the callout yourself. It gives you the ultimate level of control, but takes considerably more work. 10 | 11 | In this project, I have an abstract `CalloutView` class that renders a custom callout bubble, and has a `contentView` associated with it. In my concrete subclass of this, `ExampleCalloutView`, I add two text labels. Clearly you can do something more substantial than that, but I wanted to do enough here so that you could see that you have fine-grained control over the appearance (in this case, changing the background color and the `UIBezierPath` shape around the callout). 12 | 13 | I have also expanded this to detect taps on the callout, namely (a) adding a `hitTest` to the annotation view to included the callout, if present; and (b) added `hitTest` to callout base class to detect taps within the bubble. There is now a method, `didTouchUpInCallout`, that you can override if you want to take some action when the callout's `contentView` is tapped. 14 | 15 | This is not intended as an end-user library, but just a "simple" example of how one might create custom callouts. This is for illustrative purposes only. 16 | 17 | See http://stackoverflow.com/a/30824051/1271826. 18 | 19 | Developed in Swift on Xcode 8.1 for iOS 10 using Swift 3, but updated for Xcode 11.5 and Swift 5.2. See the `swift2` branch for Swift 2 on iOS 9. But, the basic ideas are equally applicable for different versions of Swift and Objective-C. 20 | 21 | ## License 22 | 23 | Copyright © 2015-2020 Robert Ryan. All rights reserved. 24 | 25 | Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. 26 | 27 | -- 28 | 29 | 15 June 2015 30 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 830D058A1B2E992700EF8033 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 830D05891B2E992700EF8033 /* AppDelegate.swift */; }; 11 | 830D058C1B2E992800EF8033 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 830D058B1B2E992800EF8033 /* ViewController.swift */; }; 12 | 830D058F1B2E992A00EF8033 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 830D058D1B2E992A00EF8033 /* Main.storyboard */; }; 13 | 830D05911B2E992C00EF8033 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 830D05901B2E992C00EF8033 /* Images.xcassets */; }; 14 | 830D05941B2E992C00EF8033 /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 830D05921B2E992C00EF8033 /* LaunchScreen.xib */; }; 15 | 830D05AA1B2E995700EF8033 /* MapKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 830D05A91B2E995700EF8033 /* MapKit.framework */; }; 16 | 837198361D5C0FC400687CBA /* CalloutView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 837198351D5C0FC400687CBA /* CalloutView.swift */; }; 17 | 837198381D5C108300687CBA /* CustomAnnotationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 837198371D5C108300687CBA /* CustomAnnotationView.swift */; }; 18 | 8371983A1D5C43B000687CBA /* ExampleCalloutView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 837198391D5C43B000687CBA /* ExampleCalloutView.swift */; }; 19 | /* End PBXBuildFile section */ 20 | 21 | /* Begin PBXFileReference section */ 22 | 830D05841B2E992300EF8033 /* SwiftMapViewCustomCallout.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftMapViewCustomCallout.app; sourceTree = BUILT_PRODUCTS_DIR; }; 23 | 830D05881B2E992600EF8033 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 24 | 830D05891B2E992700EF8033 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 25 | 830D058B1B2E992800EF8033 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; 26 | 830D058E1B2E992A00EF8033 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 27 | 830D05901B2E992C00EF8033 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; 28 | 830D05931B2E992C00EF8033 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = ""; }; 29 | 830D05A91B2E995700EF8033 /* MapKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MapKit.framework; path = System/Library/Frameworks/MapKit.framework; sourceTree = SDKROOT; }; 30 | 830D05B31B2E9E2C00EF8033 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 31 | 837198351D5C0FC400687CBA /* CalloutView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CalloutView.swift; sourceTree = ""; }; 32 | 837198371D5C108300687CBA /* CustomAnnotationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomAnnotationView.swift; sourceTree = ""; }; 33 | 837198391D5C43B000687CBA /* ExampleCalloutView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ExampleCalloutView.swift; sourceTree = ""; }; 34 | /* End PBXFileReference section */ 35 | 36 | /* Begin PBXFrameworksBuildPhase section */ 37 | 830D05811B2E992300EF8033 /* Frameworks */ = { 38 | isa = PBXFrameworksBuildPhase; 39 | buildActionMask = 2147483647; 40 | files = ( 41 | 830D05AA1B2E995700EF8033 /* MapKit.framework in Frameworks */, 42 | ); 43 | runOnlyForDeploymentPostprocessing = 0; 44 | }; 45 | /* End PBXFrameworksBuildPhase section */ 46 | 47 | /* Begin PBXGroup section */ 48 | 830D057B1B2E992200EF8033 = { 49 | isa = PBXGroup; 50 | children = ( 51 | 830D05B31B2E9E2C00EF8033 /* README.md */, 52 | 830D05861B2E992400EF8033 /* SwiftMapViewCustomCallout */, 53 | 830D05851B2E992300EF8033 /* Products */, 54 | ); 55 | sourceTree = ""; 56 | }; 57 | 830D05851B2E992300EF8033 /* Products */ = { 58 | isa = PBXGroup; 59 | children = ( 60 | 830D05841B2E992300EF8033 /* SwiftMapViewCustomCallout.app */, 61 | ); 62 | name = Products; 63 | sourceTree = ""; 64 | }; 65 | 830D05861B2E992400EF8033 /* SwiftMapViewCustomCallout */ = { 66 | isa = PBXGroup; 67 | children = ( 68 | 830D05891B2E992700EF8033 /* AppDelegate.swift */, 69 | 830D058B1B2E992800EF8033 /* ViewController.swift */, 70 | 837198371D5C108300687CBA /* CustomAnnotationView.swift */, 71 | 837198351D5C0FC400687CBA /* CalloutView.swift */, 72 | 837198391D5C43B000687CBA /* ExampleCalloutView.swift */, 73 | 830D058D1B2E992A00EF8033 /* Main.storyboard */, 74 | 830D05901B2E992C00EF8033 /* Images.xcassets */, 75 | 830D05921B2E992C00EF8033 /* LaunchScreen.xib */, 76 | 830D05871B2E992600EF8033 /* Supporting Files */, 77 | ); 78 | path = SwiftMapViewCustomCallout; 79 | sourceTree = ""; 80 | }; 81 | 830D05871B2E992600EF8033 /* Supporting Files */ = { 82 | isa = PBXGroup; 83 | children = ( 84 | 830D05A91B2E995700EF8033 /* MapKit.framework */, 85 | 830D05881B2E992600EF8033 /* Info.plist */, 86 | ); 87 | name = "Supporting Files"; 88 | sourceTree = ""; 89 | }; 90 | /* End PBXGroup section */ 91 | 92 | /* Begin PBXNativeTarget section */ 93 | 830D05831B2E992300EF8033 /* SwiftMapViewCustomCallout */ = { 94 | isa = PBXNativeTarget; 95 | buildConfigurationList = 830D05A31B2E992F00EF8033 /* Build configuration list for PBXNativeTarget "SwiftMapViewCustomCallout" */; 96 | buildPhases = ( 97 | 830D05801B2E992300EF8033 /* Sources */, 98 | 830D05811B2E992300EF8033 /* Frameworks */, 99 | 830D05821B2E992300EF8033 /* Resources */, 100 | 83E9389824B24A8F00854F30 /* SwiftLint */, 101 | ); 102 | buildRules = ( 103 | ); 104 | dependencies = ( 105 | ); 106 | name = SwiftMapViewCustomCallout; 107 | productName = SwiftMapViewCustomCallout; 108 | productReference = 830D05841B2E992300EF8033 /* SwiftMapViewCustomCallout.app */; 109 | productType = "com.apple.product-type.application"; 110 | }; 111 | /* End PBXNativeTarget section */ 112 | 113 | /* Begin PBXProject section */ 114 | 830D057C1B2E992200EF8033 /* Project object */ = { 115 | isa = PBXProject; 116 | attributes = { 117 | LastSwiftMigration = 0710; 118 | LastSwiftUpdateCheck = 0710; 119 | LastUpgradeCheck = 1020; 120 | ORGANIZATIONNAME = "Robert Ryan"; 121 | TargetAttributes = { 122 | 830D05831B2E992300EF8033 = { 123 | CreatedOnToolsVersion = 6.3.2; 124 | DevelopmentTeam = UZAPXQTVQ4; 125 | LastSwiftMigration = 0800; 126 | SystemCapabilities = { 127 | com.apple.Maps.iOS = { 128 | enabled = 1; 129 | }; 130 | }; 131 | }; 132 | }; 133 | }; 134 | buildConfigurationList = 830D057F1B2E992200EF8033 /* Build configuration list for PBXProject "SwiftMapViewCustomCallout" */; 135 | compatibilityVersion = "Xcode 3.2"; 136 | developmentRegion = en; 137 | hasScannedForEncodings = 0; 138 | knownRegions = ( 139 | en, 140 | Base, 141 | ); 142 | mainGroup = 830D057B1B2E992200EF8033; 143 | productRefGroup = 830D05851B2E992300EF8033 /* Products */; 144 | projectDirPath = ""; 145 | projectRoot = ""; 146 | targets = ( 147 | 830D05831B2E992300EF8033 /* SwiftMapViewCustomCallout */, 148 | ); 149 | }; 150 | /* End PBXProject section */ 151 | 152 | /* Begin PBXResourcesBuildPhase section */ 153 | 830D05821B2E992300EF8033 /* Resources */ = { 154 | isa = PBXResourcesBuildPhase; 155 | buildActionMask = 2147483647; 156 | files = ( 157 | 830D058F1B2E992A00EF8033 /* Main.storyboard in Resources */, 158 | 830D05941B2E992C00EF8033 /* LaunchScreen.xib in Resources */, 159 | 830D05911B2E992C00EF8033 /* Images.xcassets in Resources */, 160 | ); 161 | runOnlyForDeploymentPostprocessing = 0; 162 | }; 163 | /* End PBXResourcesBuildPhase section */ 164 | 165 | /* Begin PBXShellScriptBuildPhase section */ 166 | 83E9389824B24A8F00854F30 /* SwiftLint */ = { 167 | isa = PBXShellScriptBuildPhase; 168 | buildActionMask = 2147483647; 169 | files = ( 170 | ); 171 | inputFileListPaths = ( 172 | ); 173 | inputPaths = ( 174 | ); 175 | name = SwiftLint; 176 | outputFileListPaths = ( 177 | ); 178 | outputPaths = ( 179 | ); 180 | runOnlyForDeploymentPostprocessing = 0; 181 | shellPath = /bin/sh; 182 | shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nfi\n"; 183 | }; 184 | /* End PBXShellScriptBuildPhase section */ 185 | 186 | /* Begin PBXSourcesBuildPhase section */ 187 | 830D05801B2E992300EF8033 /* Sources */ = { 188 | isa = PBXSourcesBuildPhase; 189 | buildActionMask = 2147483647; 190 | files = ( 191 | 830D058C1B2E992800EF8033 /* ViewController.swift in Sources */, 192 | 830D058A1B2E992700EF8033 /* AppDelegate.swift in Sources */, 193 | 837198381D5C108300687CBA /* CustomAnnotationView.swift in Sources */, 194 | 8371983A1D5C43B000687CBA /* ExampleCalloutView.swift in Sources */, 195 | 837198361D5C0FC400687CBA /* CalloutView.swift in Sources */, 196 | ); 197 | runOnlyForDeploymentPostprocessing = 0; 198 | }; 199 | /* End PBXSourcesBuildPhase section */ 200 | 201 | /* Begin PBXVariantGroup section */ 202 | 830D058D1B2E992A00EF8033 /* Main.storyboard */ = { 203 | isa = PBXVariantGroup; 204 | children = ( 205 | 830D058E1B2E992A00EF8033 /* Base */, 206 | ); 207 | name = Main.storyboard; 208 | sourceTree = ""; 209 | }; 210 | 830D05921B2E992C00EF8033 /* LaunchScreen.xib */ = { 211 | isa = PBXVariantGroup; 212 | children = ( 213 | 830D05931B2E992C00EF8033 /* Base */, 214 | ); 215 | name = LaunchScreen.xib; 216 | sourceTree = ""; 217 | }; 218 | /* End PBXVariantGroup section */ 219 | 220 | /* Begin XCBuildConfiguration section */ 221 | 830D05A11B2E992F00EF8033 /* Debug */ = { 222 | isa = XCBuildConfiguration; 223 | buildSettings = { 224 | ALWAYS_SEARCH_USER_PATHS = NO; 225 | CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; 226 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 227 | CLANG_CXX_LIBRARY = "libc++"; 228 | CLANG_ENABLE_MODULES = YES; 229 | CLANG_ENABLE_OBJC_ARC = YES; 230 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 231 | CLANG_WARN_BOOL_CONVERSION = YES; 232 | CLANG_WARN_COMMA = YES; 233 | CLANG_WARN_CONSTANT_CONVERSION = YES; 234 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 235 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 236 | CLANG_WARN_EMPTY_BODY = YES; 237 | CLANG_WARN_ENUM_CONVERSION = YES; 238 | CLANG_WARN_INFINITE_RECURSION = YES; 239 | CLANG_WARN_INT_CONVERSION = YES; 240 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 241 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 242 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 243 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 244 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 245 | CLANG_WARN_STRICT_PROTOTYPES = YES; 246 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 247 | CLANG_WARN_UNREACHABLE_CODE = YES; 248 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 249 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 250 | COPY_PHASE_STRIP = NO; 251 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 252 | ENABLE_STRICT_OBJC_MSGSEND = YES; 253 | ENABLE_TESTABILITY = YES; 254 | GCC_C_LANGUAGE_STANDARD = gnu99; 255 | GCC_DYNAMIC_NO_PIC = NO; 256 | GCC_NO_COMMON_BLOCKS = YES; 257 | GCC_OPTIMIZATION_LEVEL = 0; 258 | GCC_PREPROCESSOR_DEFINITIONS = ( 259 | "DEBUG=1", 260 | "$(inherited)", 261 | ); 262 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 263 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 264 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 265 | GCC_WARN_UNDECLARED_SELECTOR = YES; 266 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 267 | GCC_WARN_UNUSED_FUNCTION = YES; 268 | GCC_WARN_UNUSED_VARIABLE = YES; 269 | IPHONEOS_DEPLOYMENT_TARGET = 10.0; 270 | MTL_ENABLE_DEBUG_INFO = YES; 271 | ONLY_ACTIVE_ARCH = YES; 272 | SDKROOT = iphoneos; 273 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 274 | }; 275 | name = Debug; 276 | }; 277 | 830D05A21B2E992F00EF8033 /* Release */ = { 278 | isa = XCBuildConfiguration; 279 | buildSettings = { 280 | ALWAYS_SEARCH_USER_PATHS = NO; 281 | CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; 282 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 283 | CLANG_CXX_LIBRARY = "libc++"; 284 | CLANG_ENABLE_MODULES = YES; 285 | CLANG_ENABLE_OBJC_ARC = YES; 286 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 287 | CLANG_WARN_BOOL_CONVERSION = YES; 288 | CLANG_WARN_COMMA = YES; 289 | CLANG_WARN_CONSTANT_CONVERSION = YES; 290 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 291 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 292 | CLANG_WARN_EMPTY_BODY = YES; 293 | CLANG_WARN_ENUM_CONVERSION = YES; 294 | CLANG_WARN_INFINITE_RECURSION = YES; 295 | CLANG_WARN_INT_CONVERSION = YES; 296 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 297 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 298 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 299 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 300 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 301 | CLANG_WARN_STRICT_PROTOTYPES = YES; 302 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 303 | CLANG_WARN_UNREACHABLE_CODE = YES; 304 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 305 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 306 | COPY_PHASE_STRIP = NO; 307 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 308 | ENABLE_NS_ASSERTIONS = NO; 309 | ENABLE_STRICT_OBJC_MSGSEND = YES; 310 | GCC_C_LANGUAGE_STANDARD = gnu99; 311 | GCC_NO_COMMON_BLOCKS = YES; 312 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 313 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 314 | GCC_WARN_UNDECLARED_SELECTOR = YES; 315 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 316 | GCC_WARN_UNUSED_FUNCTION = YES; 317 | GCC_WARN_UNUSED_VARIABLE = YES; 318 | IPHONEOS_DEPLOYMENT_TARGET = 10.0; 319 | MTL_ENABLE_DEBUG_INFO = NO; 320 | SDKROOT = iphoneos; 321 | VALIDATE_PRODUCT = YES; 322 | }; 323 | name = Release; 324 | }; 325 | 830D05A41B2E992F00EF8033 /* Debug */ = { 326 | isa = XCBuildConfiguration; 327 | buildSettings = { 328 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 329 | DEVELOPMENT_TEAM = UZAPXQTVQ4; 330 | INFOPLIST_FILE = SwiftMapViewCustomCallout/Info.plist; 331 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 332 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 333 | PRODUCT_BUNDLE_IDENTIFIER = "com.robertmryan.$(PRODUCT_NAME:rfc1034identifier)"; 334 | PRODUCT_NAME = "$(TARGET_NAME)"; 335 | SWIFT_VERSION = 5.0; 336 | }; 337 | name = Debug; 338 | }; 339 | 830D05A51B2E992F00EF8033 /* Release */ = { 340 | isa = XCBuildConfiguration; 341 | buildSettings = { 342 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 343 | DEVELOPMENT_TEAM = UZAPXQTVQ4; 344 | INFOPLIST_FILE = SwiftMapViewCustomCallout/Info.plist; 345 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 346 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 347 | PRODUCT_BUNDLE_IDENTIFIER = "com.robertmryan.$(PRODUCT_NAME:rfc1034identifier)"; 348 | PRODUCT_NAME = "$(TARGET_NAME)"; 349 | SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; 350 | SWIFT_VERSION = 5.0; 351 | }; 352 | name = Release; 353 | }; 354 | /* End XCBuildConfiguration section */ 355 | 356 | /* Begin XCConfigurationList section */ 357 | 830D057F1B2E992200EF8033 /* Build configuration list for PBXProject "SwiftMapViewCustomCallout" */ = { 358 | isa = XCConfigurationList; 359 | buildConfigurations = ( 360 | 830D05A11B2E992F00EF8033 /* Debug */, 361 | 830D05A21B2E992F00EF8033 /* Release */, 362 | ); 363 | defaultConfigurationIsVisible = 0; 364 | defaultConfigurationName = Release; 365 | }; 366 | 830D05A31B2E992F00EF8033 /* Build configuration list for PBXNativeTarget "SwiftMapViewCustomCallout" */ = { 367 | isa = XCConfigurationList; 368 | buildConfigurations = ( 369 | 830D05A41B2E992F00EF8033 /* Debug */, 370 | 830D05A51B2E992F00EF8033 /* Release */, 371 | ); 372 | defaultConfigurationIsVisible = 0; 373 | defaultConfigurationName = Release; 374 | }; 375 | /* End XCConfigurationList section */ 376 | }; 377 | rootObject = 830D057C1B2E992200EF8033 /* Project object */; 378 | } 379 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout.xcodeproj/xcuserdata/rryan.xcuserdatad/xcschemes/SwiftMapViewCustomCallout.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 65 | 66 | 67 | 68 | 78 | 80 | 86 | 87 | 88 | 89 | 90 | 91 | 97 | 99 | 105 | 106 | 107 | 108 | 110 | 111 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout.xcodeproj/xcuserdata/rryan.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | SwiftMapViewCustomCallout.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 830D05831B2E992300EF8033 16 | 17 | primary 18 | 19 | 20 | 830D05981B2E992E00EF8033 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // SwiftMapViewCustomCallout 4 | // 5 | // Created by Robert Ryan on 6/15/15. 6 | // Copyright © 2015-2016 Robert Ryan. All rights reserved. 7 | // 8 | // This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. 9 | // http://creativecommons.org/licenses/by-sa/4.0/ 10 | 11 | import UIKit 12 | 13 | @UIApplicationMain 14 | class AppDelegate: UIResponder, UIApplicationDelegate { 15 | 16 | var window: UIWindow? 17 | 18 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { 19 | // Override point for customization after application launch. 20 | return true 21 | } 22 | 23 | func applicationWillResignActive(_ application: UIApplication) { 24 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 26 | } 27 | 28 | func applicationDidEnterBackground(_ application: UIApplication) { 29 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 31 | } 32 | 33 | func applicationWillEnterForeground(_ application: UIApplication) { 34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 35 | } 36 | 37 | func applicationDidBecomeActive(_ application: UIApplication) { 38 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 39 | } 40 | 41 | func applicationWillTerminate(_ application: UIApplication) { 42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 20 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/CalloutView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CalloutView.swift 3 | // SwiftMapViewCustomCallout 4 | // 5 | // Created by Robert Ryan on 8/7/16. 6 | // Copyright © 2015-2016 Robert Ryan. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import MapKit 11 | 12 | /// This callout view is used to render a custom callout bubble for an annotation view. 13 | /// The size of this is dictated by the constraints that are established between the 14 | /// this callout view's `contentView` and its subviews (e.g. if those subviews have their 15 | /// own intrinsic size). Or, alternatively, you always could define explicit width and height 16 | /// constraints for the callout. 17 | /// 18 | /// This is an abstract class that you won't use by itself, but rather subclass to and fill 19 | /// with the appropriate content inside the `contentView`. But this takes care of all of the 20 | /// rendering of the bubble around the callout. 21 | 22 | class CalloutView: UIView { 23 | 24 | /// The annotation for which this callout has been created. 25 | 26 | weak var annotation: MKAnnotation? 27 | 28 | /// Shape of pointer at the bottom of the callout bubble 29 | /// 30 | /// - rounded: Circular, rounded pointer. 31 | /// - straight: Straight lines for pointer. The angle is measured in radians, must be greater than 0 and less than `.pi` / 2. Using `.pi / 4` yields nice 45 degree angles. 32 | 33 | enum BubblePointerType { 34 | case rounded 35 | case straight(angle: CGFloat) 36 | } 37 | 38 | /// Shape of pointer at bottom of the callout bubble, pointing at annotation view. 39 | 40 | private let bubblePointerType = BubblePointerType.rounded 41 | 42 | /// Insets for rounding of callout bubble's corners 43 | /// 44 | /// The "bottom" is amount of rounding for pointer at the bottom of the callout 45 | 46 | private let inset = UIEdgeInsets(top: 5, left: 5, bottom: 10, right: 5) 47 | 48 | /// Shape layer for callout bubble 49 | 50 | private let bubbleLayer: CAShapeLayer = { 51 | let layer = CAShapeLayer() 52 | layer.strokeColor = UIColor.black.cgColor 53 | layer.fillColor = UIColor.blue.cgColor 54 | layer.lineWidth = 0.5 55 | return layer 56 | }() 57 | 58 | /// Content view for annotation callout view 59 | /// 60 | /// This establishes the constraints between the `contentView` and the `CalloutView`, 61 | /// leaving enough padding for the chrome of the callout bubble. 62 | 63 | let contentView: UIView = { 64 | let contentView = UIView() 65 | contentView.translatesAutoresizingMaskIntoConstraints = false 66 | return contentView 67 | }() 68 | 69 | init(annotation: MKAnnotation) { 70 | self.annotation = annotation 71 | 72 | super.init(frame: .zero) 73 | 74 | configureView() 75 | } 76 | 77 | required init?(coder aDecoder: NSCoder) { 78 | fatalError("init(coder:) has not been implemented") 79 | } 80 | 81 | /// Configure the view. 82 | 83 | private func configureView() { 84 | translatesAutoresizingMaskIntoConstraints = false 85 | 86 | addSubview(contentView) 87 | NSLayoutConstraint.activate([ 88 | contentView.topAnchor.constraint(equalTo: topAnchor, constant: inset.top / 2.0), 89 | contentView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -inset.bottom - inset.right / 2.0), 90 | contentView.leftAnchor.constraint(equalTo: leftAnchor, constant: inset.left / 2.0), 91 | contentView.rightAnchor.constraint(equalTo: rightAnchor, constant: -inset.right / 2.0), 92 | contentView.widthAnchor.constraint(greaterThanOrEqualToConstant: inset.left + inset.right), 93 | contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: inset.top + inset.bottom) 94 | ]) 95 | 96 | addBackgroundButton(to: contentView) 97 | 98 | layer.insertSublayer(bubbleLayer, at: 0) 99 | } 100 | 101 | // if the view is resized, update the path for the callout bubble 102 | 103 | override func layoutSubviews() { 104 | super.layoutSubviews() 105 | 106 | updatePath() 107 | } 108 | 109 | // Override hitTest to detect taps within our callout bubble 110 | 111 | override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { 112 | let contentViewPoint = convert(point, to: contentView) 113 | return contentView.hitTest(contentViewPoint, with: event) 114 | } 115 | } 116 | 117 | // MARK: - Public interface 118 | 119 | extension CalloutView { 120 | /// Callout tapped. 121 | /// 122 | /// If you want to detect a tap on the callout, override this method. By default, this method does nothing. 123 | /// 124 | /// - Parameter sender: The actual hidden button that was tapped, not the callout, itself. 125 | 126 | @objc func didTouchUpInCallout(_ sender: Any) { 127 | // this is intentionally blank 128 | } 129 | 130 | /// Add this `CalloutView` to an annotation view (i.e. show the callout on the map above the pin) 131 | /// 132 | /// - Parameter annotationView: The annotation to which this callout is being added. 133 | 134 | func add(to annotationView: MKAnnotationView) { 135 | annotationView.addSubview(self) 136 | 137 | // constraints for this callout with respect to its superview 138 | 139 | NSLayoutConstraint.activate([ 140 | bottomAnchor.constraint(equalTo: annotationView.topAnchor, constant: annotationView.calloutOffset.y), 141 | centerXAnchor.constraint(equalTo: annotationView.centerXAnchor, constant: annotationView.calloutOffset.x) 142 | ]) 143 | } 144 | } 145 | 146 | // MARK: - Private methods 147 | 148 | private extension CalloutView { 149 | 150 | /// Update `UIBezierPath` for callout bubble 151 | /// 152 | /// The setting of the bubblePointerType dictates whether the pointer at the bottom of the 153 | /// bubble has straight lines or whether it has rounded corners. 154 | 155 | func updatePath() { 156 | let path = UIBezierPath() 157 | var point = CGPoint(x: bounds.width - inset.right, y: bounds.height - inset.bottom) 158 | var controlPoint: CGPoint 159 | 160 | path.move(to: point) 161 | 162 | switch bubblePointerType { 163 | case .rounded: 164 | addRoundedCalloutPointer(to: path) 165 | 166 | case .straight(let angle): 167 | addStraightCalloutPointer(to: path, angle: angle) 168 | } 169 | 170 | // bottom left 171 | 172 | point.x = inset.left 173 | path.addLine(to: point) 174 | 175 | // lower left corner 176 | 177 | controlPoint = CGPoint(x: 0, y: bounds.height - inset.bottom) 178 | point = CGPoint(x: 0, y: controlPoint.y - inset.left) 179 | path.addQuadCurve(to: point, controlPoint: controlPoint) 180 | 181 | // left 182 | 183 | point.y = inset.top 184 | path.addLine(to: point) 185 | 186 | // top left corner 187 | 188 | controlPoint = CGPoint.zero 189 | point = CGPoint(x: inset.left, y: 0) 190 | path.addQuadCurve(to: point, controlPoint: controlPoint) 191 | 192 | // top 193 | 194 | point = CGPoint(x: bounds.width - inset.left, y: 0) 195 | path.addLine(to: point) 196 | 197 | // top right corner 198 | 199 | controlPoint = CGPoint(x: bounds.width, y: 0) 200 | point = CGPoint(x: bounds.width, y: inset.top) 201 | path.addQuadCurve(to: point, controlPoint: controlPoint) 202 | 203 | // right 204 | 205 | point = CGPoint(x: bounds.width, y: bounds.height - inset.bottom - inset.right) 206 | path.addLine(to: point) 207 | 208 | // lower right corner 209 | 210 | controlPoint = CGPoint(x: bounds.width, y: bounds.height - inset.bottom) 211 | point = CGPoint(x: bounds.width - inset.right, y: bounds.height - inset.bottom) 212 | path.addQuadCurve(to: point, controlPoint: controlPoint) 213 | 214 | path.close() 215 | 216 | bubbleLayer.path = path.cgPath 217 | } 218 | 219 | func addRoundedCalloutPointer(to path: UIBezierPath) { 220 | // lower right 221 | var point = CGPoint(x: bounds.width / 2.0 + inset.bottom, y: bounds.height - inset.bottom) 222 | path.addLine(to: point) 223 | 224 | // right side of arrow 225 | 226 | var controlPoint = CGPoint(x: bounds.width / 2.0, y: bounds.height - inset.bottom) 227 | point = CGPoint(x: bounds.width / 2.0, y: bounds.height) 228 | path.addQuadCurve(to: point, controlPoint: controlPoint) 229 | 230 | // left of pointer 231 | 232 | controlPoint = CGPoint(x: point.x, y: bounds.height - inset.bottom) 233 | point = CGPoint(x: point.x - inset.bottom, y: controlPoint.y) 234 | path.addQuadCurve(to: point, controlPoint: controlPoint) 235 | } 236 | 237 | func addStraightCalloutPointer(to path: UIBezierPath, angle: CGFloat) { 238 | // lower right 239 | var point = CGPoint(x: bounds.width / 2.0 + tan(angle) * inset.bottom, y: bounds.height - inset.bottom) 240 | path.addLine(to: point) 241 | 242 | // right side of arrow 243 | 244 | point = CGPoint(x: bounds.width / 2.0, y: bounds.height) 245 | path.addLine(to: point) 246 | 247 | // left of pointer 248 | 249 | point = CGPoint(x: bounds.width / 2.0 - tan(angle) * inset.bottom, y: bounds.height - inset.bottom) 250 | path.addLine(to: point) 251 | } 252 | 253 | /// Add background button to callout 254 | /// 255 | /// This adds a button, the same size as the callout's `contentView`, to the `contentView`. 256 | /// The purpose of this is two-fold: First, it provides an easy method, `didTouchUpInCallout`, 257 | /// that you can `override` in order to detect taps on the callout. Second, by adding this 258 | /// button (rather than just adding a tap gesture or the like), it ensures that when you tap 259 | /// on the button, that it won't simultaneously register as a deselecting of the annotation, 260 | /// thereby dismissing the callout. 261 | /// 262 | /// This serves a similar functional purpose as `_MKSmallCalloutPassthroughButton` in the 263 | /// default system callout. 264 | /// 265 | /// - Parameter view: The view to which we're adding this button. 266 | 267 | func addBackgroundButton(to view: UIView) { 268 | let button = UIButton(type: .custom) 269 | button.translatesAutoresizingMaskIntoConstraints = false 270 | view.addSubview(button) 271 | NSLayoutConstraint.activate([ 272 | button.topAnchor.constraint(equalTo: view.topAnchor), 273 | button.bottomAnchor.constraint(equalTo: view.bottomAnchor), 274 | button.leadingAnchor.constraint(equalTo: view.leadingAnchor), 275 | button.trailingAnchor.constraint(equalTo: view.trailingAnchor) 276 | ]) 277 | button.addTarget(self, action: #selector(didTouchUpInCallout(_:)), for: .touchUpInside) 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/CustomAnnotationView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CustomAnnotationView.swift 3 | // SwiftMapViewCustomCallout 4 | // 5 | // Created by Robert Ryan on 8/7/16. 6 | // Copyright © 2015-2016 Robert Ryan. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import MapKit 11 | 12 | /// This is simple subclass of `MKPinAnnotationView` which includes reference for any currently 13 | /// visible callout bubble (if any). 14 | 15 | class CustomAnnotationView: MKPinAnnotationView { 16 | 17 | weak var calloutView: ExampleCalloutView? 18 | 19 | override var annotation: MKAnnotation? { 20 | willSet { 21 | calloutView?.removeFromSuperview() 22 | } 23 | } 24 | 25 | /// Animation duration in seconds. 26 | 27 | let animationDuration: TimeInterval = 0.25 28 | 29 | // MARK: - Initialization methods 30 | 31 | override init(annotation: MKAnnotation?, reuseIdentifier: String?) { 32 | super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) 33 | 34 | canShowCallout = false 35 | animatesDrop = true 36 | } 37 | 38 | required init?(coder aDecoder: NSCoder) { 39 | super.init(coder: aDecoder) 40 | } 41 | 42 | // MARK: - Show and hide callout as needed 43 | 44 | // If the annotation is selected, show the callout; if unselected, remove it 45 | 46 | override func setSelected(_ selected: Bool, animated: Bool) { 47 | super.setSelected(selected, animated: animated) 48 | 49 | if selected { 50 | self.calloutView?.removeFromSuperview() 51 | 52 | let calloutView = ExampleCalloutView(annotation: annotation as! MKShape) 53 | calloutView.add(to: self) 54 | self.calloutView = calloutView 55 | 56 | if animated { 57 | calloutView.alpha = 0 58 | UIView.animate(withDuration: animationDuration) { 59 | calloutView.alpha = 1 60 | } 61 | } 62 | } else { 63 | guard let calloutView = calloutView else { return } 64 | 65 | if animated { 66 | UIView.animate(withDuration: animationDuration, animations: { 67 | calloutView.alpha = 0 68 | }, completion: { _ in 69 | calloutView.removeFromSuperview() 70 | }) 71 | } else { 72 | calloutView.removeFromSuperview() 73 | } 74 | } 75 | } 76 | 77 | // Make sure that if the cell is reused that we remove it from the super view. 78 | 79 | override func prepareForReuse() { 80 | super.prepareForReuse() 81 | 82 | calloutView?.removeFromSuperview() 83 | } 84 | 85 | // MARK: - Detect taps on callout 86 | 87 | // Per the Location and Maps Programming Guide, if you want to detect taps on callout, 88 | // you have to expand the hitTest for the annotation itself. 89 | 90 | override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { 91 | if let hitView = super.hitTest(point, with: event) { return hitView } 92 | 93 | if let calloutView = calloutView { 94 | let pointInCalloutView = convert(point, to: calloutView) 95 | return calloutView.hitTest(pointInCalloutView, with: event) 96 | } 97 | 98 | return nil 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/ExampleCalloutView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ExampleCalloutView.swift 3 | // SwiftMapViewCustomCallout 4 | // 5 | // Created by Robert Ryan on 8/10/16. 6 | // Copyright © 2015-2016 Robert Ryan. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import MapKit 11 | 12 | protocol ExampleCalloutViewDelegate: class { 13 | func mapView(_ mapView: MKMapView, didTapDetailsButton button: UIButton, for annotation: MKAnnotation) 14 | } 15 | 16 | /// Callout that shows title and subtitle 17 | /// 18 | /// This is concrete subclass of `CalloutView` that has two labels. Note, to 19 | /// have the callout resized appropriately, all this class needed to do was 20 | /// update is the constraints between these two labels (which have intrinsic 21 | /// sizes based upon the text contained therein) and the `contentView`. 22 | /// Autolayout takes care of everything else. 23 | /// 24 | /// Note, I've added observers for the `title` and `subtitle` properties of 25 | /// the annotation view. Generally you don't need to worry about that, but it 26 | /// can be useful if you're retrieving details about the annotation asynchronously 27 | /// but you want to show the pin while that's happening. You just want to make sure 28 | /// that when the annotation's relevant properties are retrieved, that we update 29 | /// this callout view (if it's being shown at all). 30 | 31 | class ExampleCalloutView: CalloutView { 32 | 33 | private var titleLabel: UILabel = { 34 | let label = UILabel() 35 | label.translatesAutoresizingMaskIntoConstraints = false 36 | label.textColor = .white 37 | label.font = .preferredFont(forTextStyle: .callout) 38 | 39 | return label 40 | }() 41 | 42 | private var subtitleLabel: UILabel = { 43 | let label = UILabel() 44 | label.translatesAutoresizingMaskIntoConstraints = false 45 | label.textColor = .white 46 | label.font = .preferredFont(forTextStyle: .caption1) 47 | 48 | return label 49 | }() 50 | 51 | private var detailsButton: UIButton = { 52 | let button = UIButton(type: .roundedRect) 53 | button.translatesAutoresizingMaskIntoConstraints = false 54 | button.setTitle("Details", for: .normal) 55 | button.setTitleColor(.white, for: .normal) 56 | button.backgroundColor = .lightGray 57 | button.layer.cornerRadius = 3 58 | 59 | return button 60 | }() 61 | 62 | override init(annotation: MKAnnotation) { 63 | super.init(annotation: annotation) 64 | 65 | configure() 66 | 67 | updateContents(for: annotation) 68 | } 69 | 70 | required init?(coder aDecoder: NSCoder) { 71 | fatalError("Should not call init(coder:)") 72 | } 73 | 74 | /// Update callout contents 75 | 76 | private func updateContents(for annotation: MKAnnotation) { 77 | titleLabel.text = annotation.title ?? "Unknown" 78 | subtitleLabel.text = annotation.subtitle ?? nil 79 | } 80 | 81 | /// Add constraints for subviews of `contentView` 82 | 83 | private func configure() { 84 | translatesAutoresizingMaskIntoConstraints = false 85 | 86 | contentView.addSubview(titleLabel) 87 | contentView.addSubview(subtitleLabel) 88 | contentView.addSubview(detailsButton) 89 | detailsButton.addTarget(self, action: #selector(didTapDetailsButton(_:)), for: .touchUpInside) 90 | 91 | let views: [String: UIView] = [ 92 | "titleLabel": titleLabel, 93 | "subtitleLabel": subtitleLabel, 94 | "detailsButton": detailsButton 95 | ] 96 | 97 | let vflStrings = [ 98 | "V:|-[titleLabel]-[subtitleLabel]-[detailsButton]-|", 99 | "H:|-[titleLabel]-|", 100 | "H:|-[subtitleLabel]-|", 101 | "H:|-[detailsButton]-|" 102 | ] 103 | 104 | for vfl in vflStrings { 105 | contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: vfl, metrics: nil, views: views)) 106 | } 107 | } 108 | 109 | // This is an example method, defined by `CalloutView`, which is called when you tap on the callout 110 | // itself (but not one of its subviews that have user interaction enabled). 111 | 112 | override func didTouchUpInCallout(_ sender: Any) { 113 | print("didTouchUpInCallout") 114 | } 115 | 116 | /// Callout detail button was tapped 117 | /// 118 | /// This is an example action method for tapping the button we added in this subclass. 119 | /// You'd probably either have a button like this method, or not have a button and use 120 | /// the above `didTouchUpCallout`, above, but not both. But I'm showing both, so you 121 | /// can pick whichever you prefer. 122 | /// 123 | /// If you want the view controller to do something when you tap on the button, you would: 124 | /// 125 | /// - Want to declare a protocol to which your map view delegate will conform; and 126 | /// - Actually see if map view's delegate conforms to this protocol and, if so, call the method. 127 | /// 128 | /// - Parameter sender: The button we tapped on in the callout. 129 | 130 | @objc func didTapDetailsButton(_ sender: UIButton) { 131 | if let mapView = mapView, let delegate = mapView.delegate as? ExampleCalloutViewDelegate { 132 | delegate.mapView(mapView, didTapDetailsButton: sender, for: annotation!) 133 | } 134 | } 135 | 136 | /// Map view 137 | /// 138 | /// Navigate up view hierarchy until we find `MKMapView`. 139 | 140 | var mapView: MKMapView? { 141 | var view = superview 142 | while view != nil { 143 | if let mapView = view as? MKMapView { return mapView } 144 | view = view?.superview 145 | } 146 | return nil 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIMainStoryboardFile 28 | Main 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /SwiftMapViewCustomCallout/ViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.swift 3 | // SwiftMapViewCustomCallout 4 | // 5 | // Created by Robert Ryan on 6/15/15. 6 | // Copyright © 2015-2016 Robert Ryan. All rights reserved. 7 | // 8 | // This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. 9 | // http://creativecommons.org/licenses/by-sa/4.0/ 10 | 11 | import UIKit 12 | import MapKit 13 | 14 | class ViewController: UIViewController { 15 | 16 | @IBOutlet weak var mapView: MKMapView! 17 | 18 | override func viewDidLoad() { 19 | super.viewDidLoad() 20 | // Do any additional setup after loading the view, typically from a nib. 21 | } 22 | 23 | @IBAction func didTapButton(_ sender: UIButton) { 24 | addAnnotation(for: mapView.centerCoordinate) 25 | } 26 | 27 | let geocoder = CLGeocoder() 28 | 29 | func addAnnotation(for coordinate: CLLocationCoordinate2D) { 30 | let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) 31 | geocoder.reverseGeocodeLocation(location) { placemarks, _ in 32 | if let placemark = placemarks?.first { 33 | let annotation = MKPointAnnotation() 34 | annotation.coordinate = coordinate 35 | annotation.title = placemark.name 36 | annotation.subtitle = placemark.locality 37 | self.mapView.addAnnotation(annotation) 38 | } 39 | } 40 | } 41 | } 42 | 43 | // MARK: - MKMapViewDelegate 44 | 45 | extension ViewController: MKMapViewDelegate { 46 | 47 | /// show custom annotation view 48 | 49 | func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 50 | if annotation is MKUserLocation { return nil } 51 | 52 | if #available(iOS 11.0, *) { 53 | if annotation is MKClusterAnnotation { return nil } 54 | } 55 | 56 | let customAnnotationViewIdentifier = "MyAnnotation" 57 | 58 | var pin = mapView.dequeueReusableAnnotationView(withIdentifier: customAnnotationViewIdentifier) 59 | if pin == nil { 60 | pin = CustomAnnotationView(annotation: annotation, reuseIdentifier: customAnnotationViewIdentifier) 61 | } else { 62 | pin?.annotation = annotation 63 | } 64 | return pin 65 | } 66 | 67 | func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { 68 | print("mapView(_:annotationView:calloutAccessoryControlTapped)") 69 | } 70 | } 71 | 72 | // If you want view controller to be able to do something when you tap button in callout, conform to this protocol 73 | // and implement this method. 74 | 75 | extension ViewController: ExampleCalloutViewDelegate { 76 | func mapView(_ mapView: MKMapView, didTapDetailsButton button: UIButton, for annotation: MKAnnotation) { 77 | print("mapView(_:didTapDetailsButton:for:)") 78 | } 79 | } 80 | --------------------------------------------------------------------------------