ios - 在 Alamofire 关闭中添加公告
问题描述
我正在尝试在地图上添加来自服务器的位置和标题标签的注释,我尝试这样做是为了
Services.MyService(pagingParams: pagingparam1, completed: {ret in
self.getAdverts = ret
for elements in self.getAdverts{
let coordinates : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: CLLocationDegrees(elements.LOCATIONS[0])!, longitude: CLLocationDegrees(elements.LOCATIONS[1])!)
pinCords.coordinate = coordinates
pinCords.title = String(elements.PRICE!)
self.map.addAnnotation(pinCords)
}
})
在 MKMapViewDelegate 我尝试显示 annocations :
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation == true
{
return nil
}
let av = MKAnnotationView(annotation: annotation, reuseIdentifier: "offercount")
let annoIcon = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
annoIcon.contentMode = .scaleAspectFit
annoIcon.image = UIImage(named: "cancel-red")
lbl.text = annotation.title!
lbl.backgroundColor = UIColor.clear
lbl.textAlignment = .center
lbl.textColor = .white
lbl.alpha = 1
lbl.numberOfLines = 1
lbl.adjustsFontSizeToFitWidth = true
lbl.font = UIFont.systemFont(ofSize: 12)
lbl.layer.masksToBounds = true
av.backgroundColor = AreaColors.advertColor
av.canShowCallout = true
av.frame = CGRect(x: 0, y: 0, width: annoIcon.frame.size.width + lbl.frame.size.width + 4, height: 20)
av.layer.cornerRadius = av.layer.bounds.height/4
let pinlbl = UILabel(frame: CGRect(x:av.layer.bounds.width/2-10, y:av.layer.bounds.height-10, width:20, height:20))
pinlbl.layer.masksToBounds = true
pinlbl.layer.cornerRadius = 20
pinlbl.backgroundColor = AreaColors.advertColor
av.addSubview(pinlbl)
av.addSubview(annoIcon)
av.addSubview(lbl)
return av
}
只有 1annocation.title
出现其他人没有。但是当我点击任何公告时,我可以看到标题。
我认为问题是异步关闭,但我真的没有解决它。难道我做错了什么?
解决方案
看起来您正在重用您的lbl
并将其添加到每个注释中,因此您只能在最后一个注释中看到它。您必须UILabel
为每个注释创建新注释并将其添加为子视图,就像您使用 一样pinlbl
,因为您现在拥有的是lbl
从上一个注释中删除并将其重新添加到下一个注释,直到它停止并保留它在地图上的最后一个注释中。
只需更改以下内容
annoIcon.image = UIImage(named: "cancel-red")
// create new label here
let lbl = UILabel()
// the rest of your code can stay the same
推荐阅读
- python - 即使指定了 POST,Flask 也会返回 405 Method Not Allowed
- python - Django 管理.py
- javascript - 为什么返回时来自 React Router Dom 的链接不刷新?
- c# - 为什么旋转时间为 0.5 秒?
- java - Oracle AQ java实现enque/deque
- javascript - 在 Angular JS 中删除下划线并添加财政年度
- python - Python脚本单独工作,但通过nodejs子进程运行时没有这样的文件
- c - 递归函数 VS If-Else
- c# - 使用 RegEx 只允许一个字符的两个实例
- amazon-ec2 - 使用 Chef-Solo 在 Spinnaker Pipeline 中烘焙 AMI