如何在Swift4中使段控制工作?
问题描述:
我已创建自定义视图这样的:如何在Swift4中使段控制工作?
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测试版。
答
我猜你是设置选择的方式导致了问题 改变它
segmentedControl.addTarget(self, action: #selector(mapTypeChanged), for: .valueChanged)
并添加@IBAction您mapTypeChanged像
@IBAction func mapTypeChanged(segControl: UISegmentedControl) {
答
真正的答案是的混合另外两个。
segmentedControl.addTarget(self, action: #selector(mapTypeChanged:), for: .valueChanged)
+0
没有工作。更多的红色警告 – KawaiKx
我想'loadView'完全不叫和地图视图是'nil'。也许你的意思是'viewDidLoad' – vadian
调用loadView并显示地图。当我尝试更改地图类型时,应用程序崩溃。 – KawaiKx
你会得到什么错误?未知选择器? – vadian