Type ‘MapViewController’ has no member 'mapTypeChanged’
针对《iOS编程(第六版)》第六章源代码出现Type ‘MapViewController’ has no member 的问题,下面给出我的解决办法。
原代码
import Foundation
import MapKit
class MapViewController: UIViewController {
var mapView: MKMapView!
override func loadView() {
mapView = MKMapView()
view = mapView
let segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satallite"])
segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5);
segmentedControl.selectedSegmentIndex = 0
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedControl)
let topConstraint = segmentedControl.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
let margins = view.layoutMarginsGuide
let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
topConstraint.isActive = true
leadingConstraint.isActive = true
trailingConstraint.isActive = true
segmentedControl.addTarget(self, action: #selector(MapViewController.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
default:
break
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
修改后
import Foundation
import MapKit
class MapViewController: UIViewController {
var mapView: MKMapView!
override func loadView() {
mapView = MKMapView()
view = mapView
let segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satallite"])
segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5);
segmentedControl.selectedSegmentIndex = 0
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedControl)
let topConstraint = segmentedControl.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
let margins = view.layoutMarginsGuide
let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
topConstraint.isActive = true
leadingConstraint.isActive = true
trailingConstraint.isActive = true
segmentedControl.addTarget(self, action: #selector(MapViewController.mapTypeChanged(_ :)), for: .valueChanged)
}
** 修改处 **
@objc func mapTypeChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .hybrid
case 2:
mapView.mapType = .satellite
default:
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
希望对你有帮助,谢谢!