首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Alamofire闭包中添加注释

在Alamofire闭包中添加注释
EN

Stack Overflow用户
提问于 2020-11-05 21:56:28
回答 1查看 31关注 0票数 0

我正在尝试在地图上添加注记,其中的位置和标题标注来自服务器,我尝试这样做

代码语言:javascript
复制
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中,我尝试显示注释:

代码语言:javascript
复制
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
}

在绿色视图中有一个标签,下面是图像

只有一个annocation.title出现了,但当我点击任何注释时,我都能看到标题。

我认为问题是异步关闭,但我真的没有解决它。我做错了什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-05 22:09:26

看起来您正在重用lbl并将其添加到每个批注中,因此您只能在最后一个批注中看到它。您必须为每个注释创建新的UILabel,并像处理pinlbl一样将其添加为子视图,因为您现在要做的是从前一个注释中删除lbl,然后将其重新添加到下一个注释中,直到它停止并将其保留在地图上的最后一个注释中。

只需更改以下内容

代码语言:javascript
复制
annoIcon.image = UIImage(named: "cancel-red")
// create new label here
let lbl = UILabel()

// the rest of your code can stay the same
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64698695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档