如何解决尝试在 Swift MapView 中进行自定义标注并更改标记颜色
我对 Swift 和 Xcode 非常陌生,所以如果你能回答我的问题,请保持友善,不要做任何假设:-)。
我想在使用自定义图标和自定义标注视图的地图上添加自定义注释。
我找到了可以执行自定义标注 (Swift - Custom MKAnnotationView,set label title) 的代码,但是这不允许我的自定义图标工作。
这是我的代码
func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// myCustomAnnotation allows me to send private data so I can change things like marker color
guard let annotation = annotation as? myCustomAnnotation
else {
return nil
}
/* This is the code for doing the "Hello World" callout
var customCallout = mapView.dequeueReusableAnnotationView(withIdentifier: "MyMarker")
if customCallout == nil
{
customCallout = CustomAnnotationView.init(annotation: annotation,reuseIdentifier: "MyMarker")
customCallout?.setSelected(true,animated: true)
}
// End of code for custom callout
// Start of code for changing Marker color and custom image for marker
let annotationView = MKMarkerAnnotationView(annotation: annotation,reuseIdentifier: "MyMarker")
annotationView.markerTintColor = UIColor.yellow
let annotationColor: String = annotation.annotationColor!
annotationView.glyphImage = UIImage(named: "myCustomImage")
// End of code for changing color of marker and changing image of marker
// If I return annotationView then the pin color changes and the custom icon for the pin shows but the "Hello World" Box does not show
//return annotationView
// This will cause the "Hello World" to show but the default pin icon and color is used
// Looking for a way to do both
return customCallout
}
// Code for custom Marker
class CustomAnnotationView : MKPinAnnotationView
{
let selectedLabel:UILabel = UILabel.init(frame:CGRect(x: 0,y: 0,width: 140,height: 38))
override func setSelected(_ selected: Bool,animated: Bool)
{
super.setSelected(false,animated: animated)
if(selected)
{
// Do customization,for example:
selectedLabel.text = "Hello World!!"
selectedLabel.textAlignment = .center
selectedLabel.font = UIFont.init(name: "HelveticaBold",size: 15)
selectedLabel.backgroundColor = UIColor.lightGray
selectedLabel.layer.borderColor = UIColor.darkGray.cgColor
selectedLabel.layer.borderWidth = 2
selectedLabel.layer.cornerRadius = 5
selectedLabel.layer.masksToBounds = true
selectedLabel.center.x = 0.5 * self.frame.size.width;
selectedLabel.center.y = -0.5 * selectedLabel.frame.height;
self.addSubview(selectedLabel)
}
else
{
selectedLabel.removeFromSuperview()
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。