簡體   English   中英

在 Alamofire 閉包中添加注解

[英]Add Annocation in Alamofire closure

我正在嘗試在地圖上添加來自服務器的位置和標題標簽的注釋,我嘗試這樣做

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
}

綠色視圖中有一個標簽,其圖像如下在此處輸入圖片說明

只有 1 annocation.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM