[类型'MapViewController'没有成员'mapTypeChanged'] [2] 在线:
action: #selector(MapViewController.mapTypeChanged(_:)),
代码底部有一个方法mapTypeChanged
,所以我不确定为什么错误说没有成员mapTypeChanged
?我猜想mapTypeChanged需要声明为变量(全局?)
import UIKit
import MapKit
class MapViewController: UIViewController {
var mapView: MKMapView!
override func loadView() {
mapView = MKMapView()
view = mapView
let segmentedControl
= UISegmentedControl(items: ["Standard", "Hybrid", "Satellite"])
segmentedControl.backgroundColor
= UIColor.white.withAlphaComponent(0.5)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self,
action: #selector(MapViewController.mapTypeChanged(_:)),
for: .valueChanged)
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedControl)
let topConstraint
= segmentedControl.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 8)
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
func mapTypeChanged(_segControl: UISegmentedControl) {
switch _segControl.selectedSegmentIndex {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .hybrid
case 2:
mapView.mapType = .satellite
default:
break
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
print("MapViewController Loaded its view.")
}
}
答案 0 :(得分:2)
#selector(MapViewController.mapTypeChanged(_:))
表示“调用mapTypeChanged
方法”。
所以你需要实现mapTypeChanged
。
func mapTypeChanged(_ sender: UISegmentedControl) {
print(sender.selectedSegmentIndex)
}
答案 1 :(得分:1)
对于Xcode 9.3.1,函数mapTypeChanged必须在 override func loadView()
之外,并且前面是@objc:
@objc func mapTypeChanged(_ segControl: UISegmentedControl) {
switch segControl.selectedSegmentIndex {
case 0:
...
}
}
@objc属性使您的Swift API在Objective-C和Objective-C运行时可用。