gpt4 book ai didi

ios - 如何在 Swift 中的注释 View 上显示不同的图标?

转载 作者:行者123 更新时间:2023-11-30 10:58:45 27 4
gpt4 key购买 nike

我是 swift 新手。我正在使用 AR 注释 View 创建一个 AR 应用程序,其中我创建了一个要在注释 AR View 上显示的地点对象,但我无法根据 AR View 中的位置显示不同的图标。我只得到所有地方的一个特定图标。请查看我的代码来帮助我解决这个问题。非常感谢!

Here is my code:

import UIKit
import AVFoundation

protocol AnnotationViewDelegate {
func didTouch(annotationView: AnnotationView)
}


class AnnotationView: ARAnnotationView {


var titleLabel: UILabel?
var distanceLabel: UILabel?
var delegate: AnnotationViewDelegate?

var backgroundView: UIView?

var pinImage: UIImageView?

let pinoImage = ["bakeries", "banks", "barber", "bars", "beaches", "breweries", "cardealer", "carrepair", "church", "cinema",
"coffee", "college", "dentist", "dining", "doctors", "drycleaning", "fastfood", "firetruck", "fitness", "gas",
"grocery", "hospital", "hotel", "library", "lounges", "motorcycledealers", "musicvenues", "park", "petstore",
"pharmacy", "police", "postoffice", "train", "transportation", "zoo"]



override func didMoveToSuperview() {
super.didMoveToSuperview()

loadUI()
}



func getRandomColor() -> UIColor{

let red:CGFloat = CGFloat(drand48())
let green:CGFloat = CGFloat(drand48())
let blue:CGFloat = CGFloat(drand48())

return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}

func loadUI() {
titleLabel?.removeFromSuperview()
distanceLabel?.removeFromSuperview()
backgroundView?.removeFromSuperview()
pinImage?.removeFromSuperview()

backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 70))
backgroundView?.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)

backgroundView?.layer.cornerRadius = 10.0
self.addSubview(backgroundView!)

pinImage = UIImageView(frame: CGRect(x: 16, y: 8, width: 37.76, height: 54))


pinImage?.contentMode = UIViewContentMode.scaleAspectFit
self.backgroundView?.addSubview(pinImage!)

let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 22.0))
label.font = UIFont(name: "AvenirNext", size: 3)
label.numberOfLines = 0
label.textAlignment = .center
label.textColor = UIColor.white
self.backgroundView?.addSubview(label)
self.titleLabel = label


distanceLabel = UILabel(frame: CGRect(x: 66, y: 47, width: self.frame.size.width, height: 15.0))
distanceLabel?.textColor = UIColor.black
distanceLabel?.font = UIFont(name: "Montserrat-Regular", size: 12)
self.backgroundView?.addSubview(distanceLabel!)

if let annotation = annotation as? Place {


titleLabel?.text = annotation.placeName
distanceLabel?.text = String(format: "%.2f mi", annotation.distanceFromUser * 0.000621371)

pinImage?.image = UIImage(named: "FastFood")





}

}

override func layoutSubviews() {
super.layoutSubviews()




backgroundView?.frame = CGRect(x: 0, y: 0, width: 170, height: 80)

titleLabel?.frame = CGRect(x: 50, y: 8, width: self.frame.size.width - 66, height: 22.0)

distanceLabel?.frame = CGRect(x: 50, y: 30, width: self.frame.size.width, height: 20)
pinImage = UIImageView(frame: CGRect(x: 16, y: 8, width: 37.76, height: 54))



}


override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.didTouch(annotationView: self)

}




}

MapViewController

import UIKit
import MapKit
import CoreLocation

class MapViewController: BaseViewController, UITabBarDelegate{


@IBOutlet weak var leadingConstraints: NSLayoutConstraint!


@IBOutlet weak var mapView: MKMapView!
fileprivate let locationManager = CLLocationManager()
fileprivate var startedLoadingPOIs = false
fileprivate var places = [Place]()
fileprivate var arViewController: ARViewController!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!

var nearMeIndexSelected = NearMeIndexTitle()

var place: Place?


override func viewDidLoad() {
super.viewDidLoad()

mapView.delegate = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
locationManager.requestWhenInUseAuthorization()




}




@IBAction func showARController(_ sender: Any) {

arViewController = ARViewController()
arViewController.dataSource = self
arViewController.maxVisibleAnnotations = 30
arViewController.headingSmoothingFactor = 0.05
arViewController.setAnnotations(places)

self.present(arViewController, animated: true, completion: nil)


}


}



extension MapViewController: CLLocationManagerDelegate, MKMapViewDelegate {



func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView? {

if annotation is MKUserLocation {


mapView.tintColor = #colorLiteral(red: 0.08235294118, green: 0.7058823529, blue: 0.9450980392, alpha: 1)




return nil


} else {




let pin = mapView.view(for: annotation) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
pin.image = UIImage(named: "pins")

return pin

}



}




func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let location = locations.last!
print("Accuracy: \(location.horizontalAccuracy)")
if location.horizontalAccuracy < 100 {
manager.stopUpdatingLocation()
let span = MKCoordinateSpan(latitudeDelta: 0.013, longitudeDelta: 0.013)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.region = region
if !startedLoadingPOIs {
DispatchQueue.main.async {
self.activityIndicator.startAnimating()
}
startedLoadingPOIs = true

let loader = PlacesLoader()
loader.loadPOIS(location: location, radius: 1500) { placesDict, error in
if let dict = placesDict {
guard let placesArray = dict.object(forKey: "results") as? [NSDictionary] else { return }
for placeDict in placesArray {
let latitude = placeDict.value(forKeyPath: "geometry.location.lat") as! CLLocationDegrees
let longitude = placeDict.value(forKeyPath: "geometry.location.lng") as! CLLocationDegrees
let reference = placeDict.object(forKey: "reference") as! String
let name = placeDict.object(forKey: "name") as! String
let address = placeDict.object(forKey: "vicinity") as! String



let location = CLLocation(latitude: latitude, longitude: longitude)

let place = Place(location: location, reference: reference, name: name, address: address)


self.places.append(place)
let annotation = PlaceAnnotation(location: place.location!.coordinate, title: place.placeName)
DispatchQueue.main.async {
self.mapView.addAnnotation(annotation)
}
}


DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.mapView.isHidden = false


}
}
}
}
}
}
}


}



extension MapViewController: ARDataSource {
func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView {
let annotationView = AnnotationView()
arViewController.title = "MyApp"

annotationView.annotation = viewForAnnotation
annotationView.delegate = self
annotationView.frame = CGRect(x: 0, y: 0, width: 150, height: 50)

return annotationView
}
}

最佳答案

在Mapview类中添加以下代码

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
return nil
}
let reuseId = "reuseId"

let anView : AnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as! AnnotationView
if let annotation = annotation as? Place {
anView.titleLabel?.text = annotation.placeName
anView.distanceLabel?.text = String(format: "%.2f mi", annotation.distanceFromUser * 0.000621371)
if(annotation.placeName == "bakeries"){
anView.pinImage?.image = UIImage(named: "Bakery")
}
else{
anView.pinImage?.image = UIImage(named: "FastFood")
}
}
anView.canShowCallout = false

return anView
}

通过上面的方法可以更改pin自定义图片

关于ios - 如何在 Swift 中的注释 View 上显示不同的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53645164/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com