我创建了这样的自定义视图:
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。
答案 0 :(得分:3)
我猜你设置选择器的方式导致问题 将其更改为
segmentedControl.addTarget(self, action: #selector(mapTypeChanged), for: .valueChanged)
将@IBAction添加到mapTypeChanged中,如
@IBAction func mapTypeChanged(segControl: UISegmentedControl) {
答案 1 :(得分:0)
真正的答案是其他两个的混合。
segmentedControl.addTarget(self, action: #selector(mapTypeChanged:), for: .valueChanged)