2017-08-04 46 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