2017-08-04 22 views
0

我已創建自定義視圖這樣的:如何在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測試版。

+0

我想'loadView'完全不叫和地圖視圖是'nil'。也許你的意思是'viewDidLoad' – vadian

+0

調用loadView並顯示地圖。當我嘗試更改地圖類型時,應用程序崩潰。 – KawaiKx

+0

你會得到什麼錯誤?未知選擇器? – vadian

回答

2

我猜你是設置選擇的方式導致了問題 改變它

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

並添加@IBAction您mapTypeChanged像

@IBAction func mapTypeChanged(segControl: UISegmentedControl) { 
+0

這工作。但是我必須在func – KawaiKx

+1

之前添加@objc。那是因爲要在運行時綁定它,您將需要Obj C運行庫。在Swift 4中,這是一個變化,它永遠不會隱式地使用Obj C運行庫,所有使用Obj C運行庫的對象都需要明確提及。所以程序員和讀者知道這將在運行時被綁定到某個事件。 –

+0

蘋果文檔在這裏混淆了:https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget – KawaiKx

0

真正的答案是的混合另外兩個。

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

+0

沒有工作。更多的紅色警告 – KawaiKx