【发布时间】:2017-02-04 18:46:34
【问题描述】:
打开开关后,我想将引脚颜色从红色更改为紫色。到目前为止,我已经尝试过:
@IBAction func SwitchChanged(_ sender: Any){
if LegacySwitch.isOn == true {
annotation.pinTintColor = .purple
} else {
annotation.pinTintColor = .red
}
}
我的交换机连接到:
@IBOutlet weak var LegacySwitch: UISwitch!
我在 ViewDidLoad 中创建了我的图钉。 pin 的坐标来自另一个 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)
每当我运行应用程序时,图钉一直是红色的。当我使用断点告诉我它运行时遇到了 Action。
编辑 忘了说,我在 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
}
【问题讨论】:
-
这是因为您不能简单地在 viewDidLoad 中添加任何定义(包括“注释”)并期望在视图控制器中的任何地方都引用它。要么将其定义为全局变量,要么遍历
LocationMap中的注释集合(如果可能)以更改所有这些。这与任何子视图都是一样的。 -
我将它创建为 viewDidLoad 上方的变量。我刚刚编辑了我的问题以反映这一点。
-
if LegacySwitch.isOn == true是多余的。无需包含== true。此外,三元运算符比那里的条件更适合。annotation.pinTintColor = LegacySwitch.isOn ? .purple : .red -
您是否验证了您的
SwitchChanged代码正在执行?代码看起来不错 - 提供 pinTintColor 是正确的设置。顺便说一句,Swift 的命名约定建议函数和控件名称的首字母小写。 -
@dfd 开关更改的代码正在工作。大头针只是没有改变颜色。
标签: ios swift uiswitch mkpinannotationview