简体   繁体   English

如何在Swift4中使段控制工作?

[英]How to make segment control work in Swift4?

I have created custom view like this: 我创建了这样的自定义视图:

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

    }

} 

There are no build issues. 没有构建问题。 but when I run the app and tap on any button on segmented control, it aborts the app. 但是当我运行应用程序并点击分段控件上的任何按钮时,它会中止该应用程序。 Not able to figure out what is the issue. 无法弄清问题是什么。 I am using Xcode 9 beta. 我正在使用Xcode 9 beta。

I guess the way you are setting selector is causing the issue change it to 我想你设置选择器的方式导致问题改变它

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

And add @IBAction to your mapTypeChanged like 并将@IBAction添加到mapTypeChanged中

@IBAction func mapTypeChanged(segControl: UISegmentedControl) {

真正的答案是其他两个的混合。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM