什么给了?我不断收到的错误是在 action 参数的第一行。我试过“mapTypeChanged:”......#selector(mapTypeChanged)......等等......我不断收到黄色或红色错误。这是怎么回事?
class viewControllerForMap: UIViewController {
var mapView : MKMapView!
override func loadView() {
mapView = MKMapView()
self.view = mapView
let segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satellite"])
segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(segmentedControl)
segmentedControl.addTarget(self, action: #selector(mapTypeChanged(_:)), for: .valueChanged)
func mapTypeChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .hybrid
case 2:
mapView.mapType = .satellite
case _:
break
}
}
let topConstraint = segmentedControl.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 8)
let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor)
let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.trailingAnchor)
topConstraint.isActive = true
leadingConstraint.isActive = true
trailingConstraint.isActive = true
}
}
最佳答案
根据更新后的代码,问题似乎出在您的
func mapTypeChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .hybrid
case 2:
mapView.mapType = .satellite
case _:
break
}
}
函数当前在您的其他方法中。
它应该是这样的:
class viewControllerForMap: UIViewController {
var mapView : MKMapView!
override func loadView() {
mapView = MKMapView()
self.view = mapView
let segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satellite"])
segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(segmentedControl)
segmentedControl.addTarget(self, action: #selector(mapTypeChanged(_:)), for: .valueChanged)
let topConstraint = segmentedControl.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 8)
let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor)
let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.trailingAnchor)
topConstraint.isActive = true
leadingConstraint.isActive = true
trailingConstraint.isActive = true
}
func mapTypeChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .hybrid
case 2:
mapView.mapType = .satellite
case _:
break
}
}
}
希望对您有所帮助。
关于Swift 处理 Actions 和 Selectors 问题 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030635/