簡體   English   中英

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

[英]How to make segment control work in 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 beta。

我想你設置選擇器的方式導致問題改變它

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

並將@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