簡體   English   中英

Swift-使用UISwitch更改圖釘顏色

[英]Swift - Using a UISwitch to change Pin Color

開關打開后,我想將圖釘顏色從紅色更改為紫色。 到目前為止,我已經嘗試過:

@IBAction func SwitchChanged(_ sender: Any){
  if LegacySwitch.isOn == true {
   annotation.pinTintColor = .purple
  } else {
   annotation.pinTintColor = .red
  }
}

我的交換機已連接:

@IBOutlet weak var LegacySwitch: UISwitch!

我在ViewDidLoad中創建了我的圖釘。 引腳的坐標來自另一個ViewController。

//Map Stuff
    let Coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    annotation.coordinate = Coordinates
    LocationMap.addAnnotation(annotation)
    let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
    self.LocationMap.setRegion(region, animated: true)

每當我運行該應用程序時,該圖釘將繼續為紅色。 當我使用斷點告訴我它已運行時,遇到了該動作。

編輯我忘了提一下,我在ViewDidLoad上方創建了注釋變量。

var annotation = MyPointAnnotation()

我也有一個MKPointAnnotation類

class MyPointAnnotation: MKPointAnnotation {
    var pinTintColor: UIColor?
}

無效的事情:

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
    if LegacySwitch.isOn {
        annotationView.pinTintColor = .purple
    } else {
        annotationView.pinTintColor = .red
    }

    return annotationView
}

區分:

  • 注釋 :輕量級特性

  • 注釋視圖 :您所看到的內容 ,通過調用地圖視圖委托的mapView(_:viewFor:)在注釋的基礎上提供。

您正在更改前者,但沒有更改后者。 這方面的所有動作都發生在mapView(_:viewFor:) ,但是您沒有顯示出來-也沒有任何特定的原因會因為被更改而位於某個地方的實例變量中的注釋的屬性而被調用。 您需要替換 地圖中的注釋,以便重新生成注釋視圖。

暫無
暫無

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

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