I'm making an application with MapKit. Here's an image of how it looks:
And I want to change (Current location) title of the symbol current location from that pin.
Here's code:
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var theMap: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let location = self.locationManager.location
var latitude: Double = location.coordinate.latitude
var longitude: Double = location.coordinate.longitude
println("GPS Súradnice :: \(latitude), \(longitude)")
theMap.delegate = self
theMap.mapType = MKMapType.Standard
theMap.showsUserLocation = true
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
//--- Find Address of Current Location ---//
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
//--- CLGeocode to get address of current location ---//
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
if (error != nil)
{
println("Reverse geocoder failed with error" + error.localizedDescription)
return
}
if placemarks.count > 0
{
let pm = placemarks[0] as! CLPlacemark
self.displayLocationInfo(pm)
}
else
{
println("Problem with the data received from geocoder")
}
})
}
func displayLocationInfo(placemark: CLPlacemark?)
{
if let Placemark = placemark
{
//Stop updating kvôli vydrži baterke
locationManager.stopUpdatingLocation()
let adresa = (Placemark.thoroughfare != nil) ? Placemark.thoroughfare : "Ulica: "
let cislo = (Placemark.subThoroughfare != nil) ? Placemark.subThoroughfare : "Číslo ulice:"
let mesto = (Placemark.locality != nil) ? Placemark.locality : "Mesto: "
let stat = (Placemark.country != nil) ? Placemark.country : "Štát: "
var coordinates:CLLocationCoordinate2D = placemark!.location.coordinate
var pointAnnotation:MKPointAnnotation = MKPointAnnotation()
pointAnnotation.coordinate = coordinates
pointAnnotation.title = "\(adresa) \(cislo)"
pointAnnotation.subtitle = "\(adresa) \(cislo), \(mesto), \(stat)"
self.theMap.addAnnotation(pointAnnotation)
self.theMap.centerCoordinate = coordinates
self.theMap.selectAnnotation(pointAnnotation, animated: true)
println(mesto)
println(adresa)
println(cislo)
println(stat)
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
println("Chyba pri aktualizovaní lokácie " + error.localizedDescription)
}
}
If I get it right. You want to change blue dot. Try this.
let theLocation: MKUserLocation = theMap.userLocation
theLocation.title = "I'm here!"
//swift 3
let annotation = MKPointAnnotation()
annotation.coordinate = center
annotation.title = "title"
Annotation.subtitle = “Subtitle”
mapView.addAnnotation(annotation)
I think,http://swift3devlopment.blogspot.in/ here you get more details of MapKit
For Show blue circle mapkit in swift 2.0:
override func viewDidLoad() {
super.viewDidLoad()
//this line show blue circle location user
Mapa.showsUserLocation = true
locationManager.requestWhenInUseAuthorization();
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
else{
print("Location service disabled");
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
let region = MKCoordinateRegion(center: locValue, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
print("locations = \(locValue.latitude) \(locValue.longitude)")
Mapa.setRegion(region, animated: true)
}
Related
I am creating a yelp API app, but I am having trouble with my current location code. It seems the problem is my call to the API is happening before my values of Longitude and latitude are set, but I don't know how to rearrange my code to fix this issue. I have attached my code below lmk if you see anything I can do.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var venuesTableView: UITableView!
let locationManager = CLLocationManager()
var long: Double = 0.0
var lat: Double = 0.0
/// Central Park, NYC coordinates
let CPLatitude: Double = 40.782483
let CPLongitude: Double = -73.963540
// Menlo Park, California Coordinates
let MPLatitude: Double = 37.4539910200113
let MPLongitude: Double = -122.19097843112596
var venues: [Venue] = []
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else{return}
long = locValue.longitude
lat = locValue.latitude
print(long)
print(lat)
}
override func viewDidLoad() {
super.viewDidLoad()
venuesTableView.delegate = self
venuesTableView.dataSource = self
venuesTableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "customCell")
venuesTableView.separatorStyle = .none
retrieveVenues(latitude: lat, longitude: long, category: "eventservices",
limit: 20, sortBy: "distance", locale: "en_US") { (response, error) in
if let response = response {
self.venues = response
DispatchQueue.main.async {
self.venuesTableView.reloadData()
}
}
print("Does this work?")
print(self.long)
print(self.lat)
}
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
func userCurrentLocation(){
}
}
Create a separate function for the api call.
private func getVenues() {
retrieveVenues(latitude: lat, longitude: long, category: "eventservices",
limit: 20, sortBy: "distance", locale: "en_US") { (response, error) in
if let response = response {
self.venues = response
DispatchQueue.main.async {
self.venuesTableView.reloadData()
}
}
print("Does this work?")
print(self.long)
print(self.lat)
}
}
Then call this from the delegate method.
func locationManager(_ manager: CLLocationManager, didUpdateLocations
locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else{return}
long = locValue.longitude
lat = locValue.latitude
getVenues()
}
I am creating my first IOS app and am not a developer and am really stuck with Map Annotations.
I am trying to get Fire data from a GeoJSON URL end point and display the fires as Annotations on a Map using URLSession and a custom MKAnnotationView and custom fire Pins.
The problem is the Annotations with the GeoJSON Fire data from the URL end point are not appearing on the Map, although data is being returned by the URL session. However, if I manually create a single Fire annotation it is appearing correctly on the map with the custom pin.
Any help would be immensely appreciated, I have spent days trying to figure this out :(
Here is the ViewController.Swift file
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
var locationManager:CLLocationManager!
var lat = Double()
var lon = Double()
var fires: [Fire] = []
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.register(FireMarkerView.self,forAnnotationViewWithReuseIdentifier:
MKMapViewDefaultAnnotationViewReuseIdentifier)
if let url = URL(string: "https://services3.arcgis.com/T4QMspbfLg3qTGWY/arcgis/rest/services/Active_Fires/FeatureServer/0/query?outFields=*&where=1%3D1&f=geojson") {
URLSession.shared.dataTask(with: url) {data, response, error in
if let data = data {
do {
let features = try MKGeoJSONDecoder().decode(data)
.compactMap { $0 as? MKGeoJSONFeature }
let validWorks = features.compactMap(Fire.init)
self.fires.append(contentsOf: validWorks)
print([self.fires])
}
catch let error {
print(error)
}
}
}.resume()
}
//This code works an annotation appears correctly on map
/* let fire = Fire(
title: "Ford Fire",
incidentShortDescription: "Hwy 35",
incidentTypeCategory: "WF",
coordinate: CLLocationCoordinate2D(latitude: 37.7993, longitude: -122.1947))
mapView.addAnnotation(fire)*/
mapView.addAnnotations(fires)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineMyCurrentLocation()
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
switch manager.authorizationStatus {
case .authorizedAlways , .authorizedWhenInUse:
mapView.showsUserLocation = true
followUserLocation()
locationManager.startUpdatingLocation()
break
case .notDetermined , .denied , .restricted:
locationManager.requestWhenInUseAuthorization()
break
default:
break
}
switch manager.accuracyAuthorization {
case .fullAccuracy:
break
case .reducedAccuracy:
break
default:
break
}
}
func followUserLocation() {
if let location = locationManager.location?.coordinate {
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: 4000, longitudinalMeters: 4000)
mapView.setRegion(region, animated: true)
}
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
let userLocation = locations.first! as CLLocation
lat = userLocation.coordinate.latitude
lon = userLocation.coordinate.longitude
let region = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: 400000, longitudinalMeters: 400000)
self.mapView.setRegion(region, animated: true)
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
// Need a solution for this.
manager.stopUpdatingLocation()
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
}
Here is the Model Class, Fire.swift
import Foundation
import MapKit
class Fire: NSObject, MKAnnotation {
let title: String?
let incidentShortDescription: String?
let incidentTypeCategory: String?
let coordinate: CLLocationCoordinate2D
init(
title: String?,
incidentShortDescription: String?,
incidentTypeCategory: String?,
coordinate: CLLocationCoordinate2D
) {
self.title = title
self.incidentShortDescription = incidentShortDescription
self.incidentTypeCategory = incidentTypeCategory
self.coordinate = coordinate
super.init()
}
init?(feature: MKGeoJSONFeature) {
// 1
guard
let point = feature.geometry.first as? MKPointAnnotation,
let propertiesData = feature.properties,
let json = try? JSONSerialization.jsonObject(with: propertiesData),
let properties = json as? [String: Any]
else {
return nil
}
// 3
title = properties ["IncidentName"] as? String
incidentShortDescription = properties["IncidentShortDescription"] as? String
incidentTypeCategory = properties["IncidentTypeCategory"] as? String
coordinate = point.coordinate
super.init()
}
var subtitle: String? {
return (incidentTypeCategory)
}
var image: UIImage {
guard let name = incidentTypeCategory else {
return #imageLiteral(resourceName: "RedFlame")
}
switch name {
case "RX":
return #imageLiteral(resourceName: "YellowFlame")
default:
return #imageLiteral(resourceName: "RedFlame")
}
}
Here is the custom MKAnnotation Class: FileMarkerView.swift
import Foundation
import MapKit
class FireMarkerView: MKAnnotationView {
override var annotation: MKAnnotation? {
willSet {
guard let fire = newValue as? Fire else {
return
}
canShowCallout = true
calloutOffset = CGPoint(x: -5, y: 5)
rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
image = fire.image
}
}
}
URLSession.shared.dataTask is an asynchronous task, meaning it calls its callback function at some indeterminate time in the future. Code executed outside of its callback (the { }) will end up getting called before the data task has actually completed. Right now, you're setting the annotations outside of that callback.
To solve this, you need to set the annotations inside of that callback function. So, where you have print([self.fires]), you can do:
DispatchQueue.main.async {
self.mapView.addAnnotations(self.fires)
}
The DispatchQueue.main.async is to make sure that an update to the UI gets called on the main thread (the URL task may return on a different thread).
I tried to show the place that I want in mapView by insering latitude and longitude, but I failed to do that and the map show me always my place where I am and not the place that I want to get
these is the code that I used
class MapViewController: UIViewController, CLLocationManagerDelegate{
#IBOutlet weak var map: MKMapView!
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
map.showsPointsOfInterest = true
map.showsUserLocation = true
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
//user location stuff
if CLLocationManager.locationServicesEnabled() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
}
}
func locationManager(_manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) {
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let location = CLLocationCoordinate2D(latitude: 36.1070, longitude: -112.1130)
let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
}
Comment this
map.showsUserLocation = true
And put the code of didUpdateLocations inside viewDidLoad
class MapViewController: UIViewController, CLLocationManagerDelegate{
#IBOutlet weak var map: MKMapView!
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
map.showsPointsOfInterest = true
//map.showsUserLocation = true
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
//user location stuff
if CLLocationManager.locationServicesEnabled() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
}
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let location = CLLocationCoordinate2D(latitude: 36.1070, longitude: -112.1130)
let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
map.setRegion(region, animated: true)
}
func locationManager(_manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) {
///
}
}
To have a more reliable and efficient result,
I recommend using .plist (property list) file to store the latitude and longitude dynamically it would be much easier and would cost you less time.
plist contains the pins annotation directions which are basically an XML text file that holds the essential configuration information for bundle execution.
here is how to attach it to your project:
In your main view controller write the function:
func fetchAllData(){
if let path = Bundle.main.path(forResource: "NAME OF YOUR PLIST FILE", ofType: "plist") {
////If your plist contain root as Dictionary
if let dic = NSDictionary(contentsOfFile: path) as? [String: Any] {
let keys=dic.keys
for dataOfKey in keys {
if let object=dic[dataOfKey] as? [[String:Any]]{
locationsArray.append(contentsOf: object)
}
}
}
for location in self.locationsArray{
let newPin = MKPointAnnotation()
newPin.coordinate = CLLocationCoordinate2D.init(latitude: Double(location["latitude"] as! String)!, longitude: Double(location["longitude"] as! String)!)
self.mapView.addAnnotation(newPin)
}
}
}
I am trying to implement a background fetch for location, it works perfect inside of the iOS simulator, but when I build it on my phone, it does not appear to work. Here is my current code:
import UIKit
import CoreLocation
class CurrentConditonsViewController: UIViewController, CLLocationManagerDelegate {
lazy var locationManager: CLLocationManager! = {
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
manager.delegate = self
manager.requestAlwaysAuthorization()
manager.distanceFilter = 2000
if #available(iOS 9.0, *) {
manager.allowsBackgroundLocationUpdates = true
} else {
// Fallback on earlier versions
};
return manager
}()
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
var userLocation : String!
var userLatitude : Double!
var userLongitude : Double!
var userTemperatureCelsius : Bool!
override func viewDidLoad() {
locationManager.startUpdatingLocation();
refresh()
}
func refresh(){
initLocationManager()
}
func initLocationManager() {
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
//println(locality)
//println(postalCode)
//println(administrativeArea)
//println(country)
}
}
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
// Add another annotation to the map.
let coords = newLocation.coordinate
userLatitude = coords.latitude
userLongitude = coords.longitude
if UIApplication.sharedApplication().applicationState == .Active {
NSLog("App is in foreground. New location is %#", newLocation)
CLGeocoder().reverseGeocodeLocation(newLocation, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.displayLocationInfo(pm);
} else {
print("Problem with the data received from geocoder")
}
})
} else {
NSLog("App is backgrounded. New location is %#", newLocation)
let coord = newLocation.coordinate
let lat = coord.latitude.description;
let lng = coord.longitude.description;
let localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Project RainMan"
localNotification.alertBody = "Location Updated: " + lat + ", " + lng
localNotification.fireDate = NSDate(timeIntervalSinceNow: 8)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
}
func locationManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
var locationStatus = ""
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Status not determined"
default:
locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
if #available(iOS 9.0, *) {
locationManager.allowsBackgroundLocationUpdates = true
} else {
// Fallback on earlier versions
};
locationManager.startUpdatingLocation()
} else {
NSLog("Denied access: \(locationStatus)")
}
}
} // END OF CLASS
I do not receive any notification on my actual device, and it is worth noting this morning the code only updates the app when the app is running. I have spent a couple days on this code and am sure it's something simple, any help would be greatly appreciated!
I am using swift and I am working on a project, where I have to show a draggable map with changing location. and below the map I have subview and it have a button, on button click the subview will appear and on same button click I will disappear.
But the problem is sometime its working fine some time this view is go down and not coming on screen. and specially when I use button title change code.
class LocationMAP: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var selectAnyoneButton: UIButton!
#IBOutlet weak var selectingView: UIView!
var changingText:Bool = false
#IBOutlet weak var map: MKMapView!
var locationManger = CLLocationManager()
let geoCoder = CLGeocoder()
var myLocation: CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
self.locationManger.delegate = self
locationManger.desiredAccuracy = kCLLocationAccuracyBest
locationManger.requestWhenInUseAuthorization()
locationManger.startUpdatingLocation()
if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){
}
self.map.showsUserLocation = true
self.map.delegate = self
self.map.setUserTrackingMode(MKUserTrackingMode.Follow, animated: true)
let location = CLLocationCoordinate2DMake(20.59368, 78.96288)
let span = MKCoordinateSpanMake(0.2, 0.2)
_ = MKCoordinateRegionMake(location, span)
let annotation = MKPointAnnotation()
annotation.coordinate = (location)
selectAnyoneButton.setTitle("Submit", forState: .Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK:- MapView Delegates
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .Authorized, .AuthorizedWhenInUse:
manager.startUpdatingLocation()
self.map.showsUserLocation = true
default: break
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.myLocation = locations.last! as CLLocation
let userLocation:CLLocation = locations.last!
let long = userLocation.coordinate.longitude
let lat = userLocation.coordinate.latitude
print(long , lat)
// locationManger.stopUpdatingLocation()
self.map.centerCoordinate = myLocation.coordinate
let reg = MKCoordinateRegionMakeWithDistance(myLocation.coordinate, 1500, 1500)
self.map.setRegion(reg, animated: true)
geoCode(myLocation)
}
func geoCode(location : CLLocation!){
geoCoder.cancelGeocode()
self.locationManger.stopUpdatingLocation()
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemark, error) -> Void in
guard let placeMarks = placemark as [CLPlacemark]! else {
return
}
let loc: CLPlacemark = placeMarks[0]
let addressDict : [NSString:NSObject] = loc.addressDictionary as! [NSString: NSObject]
let addrList = addressDict["FormattedAddressLines"] as! [String]
let address = (addrList.joinWithSeparator(", "))
self.locationLabel.text = address
let lat = loc.location!.coordinate.latitude
let long = loc.location!.coordinate.longitude
print(lat , long)
SharedPreferenceManager.sharedInstance.userLatitude = lat
SharedPreferenceManager.sharedInstance.userLongitude = long
SharedPreferenceManager.sharedInstance.userAddress = address
})
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error.localizedDescription)
}
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
geoCode(location)
self.map.removeAnnotations(mapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = map.centerCoordinate
annotation.title = "title"
annotation.subtitle = "subtitle"
self.map.addAnnotation(annotation)
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView()
if #available(iOS 9.0, *) {
annotationView.pinTintColor = UIColor.blueColor()
annotationView.center = CGPointMake(160, 200)
} else {
}
return annotationView
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState
newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
if (newState == MKAnnotationViewDragState.Starting) {
view.dragState = MKAnnotationViewDragState.Dragging
}
else if (newState == MKAnnotationViewDragState.Ending || newState == MKAnnotationViewDragState.Canceling){
view.dragState = MKAnnotationViewDragState.None
}
}
//MARK:- Button Action Methods
#IBOutlet weak var downBtn: UILabel!
#IBAction func chooseButtonAction(sender: AnyObject) {
if (changingText == false) {
let newCenter:CGPoint = CGPointMake(selectingView.center.x, selectingView.center.y - 230)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.55)
selectingView.center = newCenter
UIView.commitAnimations()
selectAnyoneButton.setTitle("Select a service", forState: .Normal)
changingText = true
} else {
let newCenter:CGPoint = CGPointMake(selectingView.center.x, selectingView.center.y + 230)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.55)
selectingView.center = newCenter
UIView.commitAnimations()
selectAnyoneButton.setTitle("Submit", forState: .Normal)
changingText = false
}
}
in button's action methods, add:
super.bringSubviewToFront(UIView)
towards the end.
I am assuming your view in question is a direct child of superview.