ios - 如何使段控制在 Swift4 中工作?

标签 ios swift mapkit

我创建了这样的自定义 View :

import UIKit
import MapKit

class MapViewController: UIViewController {

    var mapView: MKMapView!

    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 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: "mapTypeChanged", for: .valueChanged)


        segmentedControl.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(segmentedControl)

        let topConstraint = segmentedControl.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 8)

        let margins = view.layoutMarginsGuide

        let leadingContraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor)

        let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor)

        topConstraint.isActive = true
        leadingContraint.isActive = true
        trailingConstraint.isActive = true

    }

} 

没有构建问题。但是当我运行该应用程序并点击分段控件上的任何按钮时,它会中止该应用程序。无法弄清楚是什么问题。我正在使用 Xcode 9 beta。

最佳答案

我猜你设置选择器的方式导致了这个问题 改成

segmentedControl.addTarget(self, action: #selector(mapTypeChanged), for: .valueChanged)

然后将@IBAction 添加到您的mapTypeChanged 中

@IBAction func mapTypeChanged(segControl: UISegmentedControl) {

关于ios - 如何使段控制在 Swift4 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45510450/

相关文章:

ios - 无法检测全屏 AVPlayerViewController 转换

ios - 我如何在输出中得不到可选?

ios - 放置在覆盖层上时 MapKit 引脚标题不可见?

iphone - 添加两个MKPolylineView

swift - MKUserTrackingButton - 如何在不缩小的情况下获取用户位置的中心 map ?

ios - 通过代码在 IB 链接的 UITextView 上设置自定义字体/颜色

ios - 在产品包中嵌入 Assets 包,Xcode 9.2

ios - 如何在 swift 中编写 if/else 语句,以便在 iOS tableview 中单击特定单元格时,它会转到特定的 viewController

ios - 录制视频并上传到 Firebase

ios - swift 正则表达式格式?