我已創建自定義視圖這樣的:如何在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測試版。
我想'loadView'完全不叫和地圖視圖是'nil'。也許你的意思是'viewDidLoad' – vadian
調用loadView並顯示地圖。當我嘗試更改地圖類型時,應用程序崩潰。 – KawaiKx
你會得到什麼錯誤?未知選擇器? – vadian