我正在阅读一本名为“iOS编程第5版”的书,由大书呆子分支。
此代码在地图视图中生成分段视图,每次在运行时更改分段时,它都会崩溃:
线程1:信号SIGABRT
当我使用最新版本时,可能与书中的旧版Swift有关。
这是我的代码:
class MapViewController: UIViewController
{
var mapView: MKMapView!
override func loadView()
{
//Create a map view
mapView = MKMapView ()
//Set it as *the* view of this view controller
view = mapView
let segmentedControl = UISegmentedControl (items: ["Standard", "Hybrid", "Satelite"])
segmentedControl.backgroundColor = UIColor.white.withAlphaComponent (0.5)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: Selector(("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()
{
// Always call the super implementation of ViewDidLoad
super.viewDidLoad()
print ("MapViewController loaded its view")
}
}
我该如何解决这个问题?
答案 0 :(得分:1)
尝试在操作方法中添加@objc
属性(同样,根据Swift 3,也可以使用_
删除参数标签):
@objc func mapTypeChanged(_ segControl: UISegmentedControl) {
...
}
作为简化(和代码大小优化),Swift 4 now further restricts哪些方法会自动向Objective-C公开 - 即使是NSObject
子类,例如上面的MapViewController
类。
顺便说一句,使用@IBAction
属性也会将您的方法暴露给Objective-C。