1

我正在关注 big nerd 分支的一本书,名为“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")
}



}

我该如何解决?

4

1 回答 1

1

尝试向您的操作方法@objc添加一个属性(此外,根据 Swift 3,也可以使用删除参数标签):_

@objc func mapTypeChanged(_ segControl: UISegmentedControl) {
    ...
}

作为一种简化(和代码大小优化),Swift 4 现在进一步限制了哪些方法会自动暴露给 Objective-C ——即使对于NSObject像上面的类这样的子类也是如此MapViewController

顺便说一句,使用该@IBAction属性也会使您的方法也暴露给 Objective-C。

于 2017-06-18T12:16:07.850 回答