Swift - 未检测到在自定义单元格中移动滑块的事件

时间:2017-07-03 18:51:54

标签: ios swift uitableview delegates slider

我正在使用以下界面在swift 3中开发一个应用程序:

enter image description here

我必须添加一些关于传奇的细节。图例包含两个视图(firstView和secondView)。默认的“布局”为0,直到我们点击它,然后打开单元格的细节。贝尔斯,这样的传奇出现了:

enter image description here

目前滑块发送事件如下:

enter image description here

界面由两个视图组成。作为底部视图的地图(“MainMapVC”),如果我们向右滑动,则显示由自定义单元格(“customCell”)形成的地图“LefSideViewController”的图例。 我附上三个类的代码:

“customCell”:

导入UIKit

protocol customCellDelegate {
    func didTappedSwicht(cell: customCell)
    func didMoveSlider(cell: customCell)
}

class customCell: UITableViewCell {

//MARK: OUTLETS VIEW 1
@IBOutlet weak var firstView: UIView!
@IBOutlet weak var firstViewLabel: UILabel!
@IBOutlet weak var swichtActiveLayer: UISwitch!


//MARK: OUTLETS VIEW 2
@IBOutlet weak var secondView: UIView!
@IBOutlet weak var secondViewLabel: UILabel!
@IBOutlet weak var secondHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var idDeliveryResponse: UILabel!
@IBOutlet weak var minRangeDeliveryResponse: UILabel!
@IBOutlet weak var maxRangeDeliveryResponse: UILabel!
@IBOutlet weak var initialMinDeliveryResponse: UILabel!
@IBOutlet weak var initialMaxDeliveryResponse: UILabel!
@IBOutlet weak var sliderOpacity: UISlider!


// MARK: VARIABLES
var delegate: customCellDelegate!

override func awakeFromNib() {
    super.awakeFromNib()
}


func setupWithModel(model: deliveriesLeftTableModel){
    firstViewLabel.text = model.firstViewLabel
    secondViewLabel.text = model.secondViewLabel
    idDeliveryResponse.text = model.idDeliveryResponse
    minRangeDeliveryResponse.text = model.minRangeDeliveryResponse
    maxRangeDeliveryResponse.text = model.maxRangeDeliveryResponse
    initialMinDeliveryResponse.text = model.initialMinDeliveryResponse
    initialMaxDeliveryResponse.text = model.initialMaxDeliveryResponse
    swichtActiveLayer.setOn(model.swichtActiveLayer, animated: true)
    sliderOpacity.value = model.sliderOpacity

}


@IBAction func swichtValueChanged(_ sender: Any) {
    delegate.didTappedSwicht(cell: self)
}


@IBAction func primaryActionTrigger(_ sender: Any){
    print("primaryActionTrigger")
}

@IBAction func touchUpInside(_ sender: Any){
    print("touchUpInside")
}

/*@IBAction func sliderValueChanged(_ sender: Any) {
    delegate.didMoveSlider(cell: self)
}*/


var showsDetails = false {
    didSet {
        secondHeightConstraint.priority = showsDetails ? 250 : 900
    }
}

}

“LefSideViewController”是:

import UIKit

protocol customCellDelegate {
    func didTappedSwicht(cell: customCell)
    func didMoveSlider(cell: customCell)
}

class customCell: UITableViewCell {

//MARK: OUTLETS VIEW 1
@IBOutlet weak var firstView: UIView!
@IBOutlet weak var firstViewLabel: UILabel!
@IBOutlet weak var swichtActiveLayer: UISwitch!


//MARK: OUTLETS VIEW 2
@IBOutlet weak var secondView: UIView!
@IBOutlet weak var secondViewLabel: UILabel!
@IBOutlet weak var secondHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var idDeliveryResponse: UILabel!
@IBOutlet weak var minRangeDeliveryResponse: UILabel!
@IBOutlet weak var maxRangeDeliveryResponse: UILabel!
@IBOutlet weak var initialMinDeliveryResponse: UILabel!
@IBOutlet weak var initialMaxDeliveryResponse: UILabel!
@IBOutlet weak var sliderOpacity: UISlider!


// MARK: VARIABLES
var delegate: customCellDelegate!

override func awakeFromNib() {
    super.awakeFromNib()
}


func setupWithModel(model: deliveriesLeftTableModel){
    firstViewLabel.text = model.firstViewLabel
    secondViewLabel.text = model.secondViewLabel
    idDeliveryResponse.text = model.idDeliveryResponse
    minRangeDeliveryResponse.text = model.minRangeDeliveryResponse
    maxRangeDeliveryResponse.text = model.maxRangeDeliveryResponse
    initialMinDeliveryResponse.text = model.initialMinDeliveryResponse
    initialMaxDeliveryResponse.text = model.initialMaxDeliveryResponse
    swichtActiveLayer.setOn(model.swichtActiveLayer, animated: true)
    sliderOpacity.value = model.sliderOpacity

}


@IBAction func swichtValueChanged(_ sender: Any) {
    delegate.didTappedSwicht(cell: self)
}



@IBAction func sliderValueChanged(_ sender: Any) {
    delegate.didMoveSlider(cell: self)
}



var showsDetails = false {
    didSet {
        secondHeightConstraint.priority = showsDetails ? 250 : 900
    }
}

}

最后一个“MainMapVC”:

import UIKit
import GoogleMaps
import MapKit
import ObjectMapper



//MARK: GLOBAL VARIABLES
let showLegend = UserDefaults.standard
let showLegendInformation = "showLegend"
var fields:WFSModel = WFSModel()
var allFields:[Field] = [Field]()
var total_parcels:[Parcel] = [Parcel]()
var poligons: [GMSPolygon] = []
var holes: [GMSMutablePath] = []
var snapShotsLegend : SnapshotsLegendModel = SnapshotsLegendModel()
var allDeliveries: [GMSURLTileLayer] = [GMSURLTileLayer]()

class MainMapVC: UIViewController, UISearchBarDelegate, CLLocationManagerDelegate, GMSMapViewDelegate {

//OUTLETS:
@IBOutlet weak var dragLegend: NSLayoutConstraint!
@IBOutlet weak var iconDragLegend: UIImageView!
@IBOutlet weak var mapView: GMSMapView!
@IBOutlet weak var timer: UIActivityIndicatorView!
@IBOutlet weak var dragLengendView: UIView!
@IBOutlet weak var iconBarLegend: UIBarButtonItem!


//MARK: VARIABLES
let layer: WMSTileOverlay
var window: UIWindow?
var centerContainer: MMDrawerController?
var url = ""
let locationManager = CLLocationManager()
var coordenatesCellSelected: [Double] =  [Double]()
var hole = GMSMutablePath()
var wfs:WFSModel = WFSModel()
var rect = GMSMutablePath()
let start = NSDate();
var polygonSelect = GMSPath()
var posSelecteTable:Int = 0
var menu_vc: LeftSideViewController!



//MARK:VIEWS
override func viewWillAppear(_ animated: Bool) {
    super.viewDidLoad()

    if coordenatesCellSelected.count != 0 {
        let bounds = GMSCoordinateBounds(path: poligons[posSelecteTable].path!)
        self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0))
        poligons[posSelecteTable].fillColor = UIColor(red: 8/256, green: 246/255, blue: 191/255, alpha: 0.9)
        poligons[posSelecteTable].strokeColor = .blue
        poligons[posSelecteTable].strokeWidth = 2
        poligons[posSelecteTable].map = mapView
    }

    if showLegend.bool(forKey: showLegendInformation) == true {

        //self.dragLengendView.isHidden = false
        self.iconBarLegend.isEnabled = true


    }
}




override func viewDidLoad() {
    super.viewDidLoad()

    menu_vc = self.storyboard?.instantiateViewController(withIdentifier: "LeftSideViewController") as! LeftSideViewController
    menu_vc.delegate = self

    self.timer.startAnimating()

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    mapView.isMyLocationEnabled = true
    mapView.settings.myLocationButton = true

    url = ""

    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToGesture))
    swipeRight.direction = UISwipeGestureRecognizerDirection.right

    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToGesture))
    swipeRight.direction = UISwipeGestureRecognizerDirection.left

    self.view.addGestureRecognizer(swipeRight)
    self.view.addGestureRecognizer(swipeLeft)

    if showLegend.bool(forKey: showLegendInformation) == false {


        self.iconBarLegend.tintColor = UIColor.clear
        self.iconBarLegend.isEnabled = false
    }


    if !allFields.isEmpty{
        drawFields()
    }

    if allFields.isEmpty{
        self.getCardfromGeoserver()
    }
    self.mapView.mapType = .satellite

}

@IBAction func menu_action(_ sender: UIBarButtonItem) {

    if AppDelegate.menu_bool{
        show_menu_left()
    }else{
        close_menu_left()
    }

}

func show_menu_left(){

    UIView.animate(withDuration: 0.6) { ()->Void in

        self.menu_vc.view.frame = CGRect(x: 0, y: 60, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
        self.menu_vc.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        self.addChildViewController(self.menu_vc)
        self.view.addSubview(self.menu_vc.view)
        AppDelegate.menu_bool = false
    }

}


func close_menu_left(){

    UIView.animate(withDuration: 0.6, animations: { ()->Void in
        self.menu_vc.view.frame = CGRect(x: -UIScreen.main.bounds.size.width, y: 60, width: -UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
    }) { (finished) in

        self.menu_vc.view.removeFromSuperview()
    }

    AppDelegate.menu_bool = true

}


func respondToGesture(gesture: UISwipeGestureRecognizer){
    switch gesture.direction{
    case UISwipeGestureRecognizerDirection.right:
        show_menu_left()

    case UISwipeGestureRecognizerDirection.left:
        close_on_swipe()

    default:
        break

    }
}

func close_on_swipe(){

    if AppDelegate.menu_bool{
        show_menu_left()
    }else{
        close_menu_left()
    }

}

//MARK: FUNCITIONS
required init?(coder aDecoder: NSCoder) {
    self.layer = WMSTileOverlay(urlArg: url)
    super.init(coder: aDecoder)
}


func getCardfromGeoserver() {
    mapView.clear()

    //mapView.camera = GMSCameraPosition(target: CLLocationCoordinate2D(latitude: 40.4256572451179, longitude: -3.18201821297407), zoom: 5.5, bearing: 0, viewingAngle: 0)


    //MAP POSITION WITH DIFERENTS LAYERS
    mapView.camera = GMSCameraPosition(target: CLLocationCoordinate2D(latitude: 39.59955969890008, longitude: -0.6421281303940684), zoom: 18.0, bearing: 0, viewingAngle: 0)






    let WFS_JSON = "http://192.168.0.160:8080/geoserver/LordWor/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=LordWor:hemav-fincas&maxFeatures=1721&outputFormat=json"

    if allFields.isEmpty {
        let mapsFacade = MapsFacade()
        mapsFacade.coordinatesWFS(url: WFS_JSON,
                      callbackFuncionOK: coordinatesWFSOK,
                      callbackFunctionERROR: coordinatesWFSOKERROR)
    }



}



func coordinatesWFSOK( WFS_Response:  WFSModel) {
    let fields = WFS_Response.copyFieldswfs()
    wfs = WFS_Response

        for feature in 1...(wfs.features.count) {
            //MARK: INSERT DATA FIELDS
            DataBaseManagement.shared.addFields(inputPropertyIDFarming : wfs.features[feature - 1].properties.propertyIDFarming,
                                                inputPropertyProducer : wfs.features[feature - 1].properties.propertyProducer,
                                                inputPropertyVariety : wfs.features[feature - 1].properties.propertyVariety,
                                                inputPropertyLand : wfs.features[feature - 1].properties.propertyLand)


            for parcel in 1...(wfs.features[feature - 1].geometry.coordinates.count) {

                if wfs.features[feature - 1].geometry.coordinates[parcel - 1].count == 1{//MARK: Without Hole
                    for poligon in 1...(wfs.features[feature - 1 ].geometry.coordinates[parcel - 1].count) {

                        //MARK: INSERT DATA FIELDS
                        DataBaseManagement.shared.addParcels(inputId_field: feature, inputCoordinatesJSON: String(describing: wfs.features[feature - 1].geometry.coordinates[0][0]))

                    }

                }else{
                    for id in 1...(wfs.features[feature - 1].geometry.coordinates[parcel - 1].count) {//MARK: With Hole

                        if id == 1{
                            //MARK: INSERT COOERDENATES PARCEL
                            DataBaseManagement.shared.addParcels(inputId_field: feature, inputCoordinatesJSON: String(describing: wfs.features[feature - 1].geometry.coordinates[0][0]))

                        }else{
                            //MARK: this row contains all points for create a hole
                           //DataBaseManagement.shared.addHoles(inputId_hole: parcel, inputCoordinatesJSON: String(describing: wfs.features[feature - 1].geometry.coordinates[0][id - 1]))
                            //print("-------FIN PARCELA HOLE \(id - 1)---------")
                        }


                    }

                }
            }

    }

    //MARK: Get all group of Parcels
if allFields.count == 0 {
    allFields = DataBaseManagement.shared.showAllFields()
    total_parcels = DataBaseManagement.shared.showAllParcels()
}

    drawFields()
}

func deleteAllParcels(){

    for i in 0...total_parcels.count - 1 {
        DataBaseManagement.shared.deleteAllParcels(inputId: i)
    }
}

func deleteAllFields(){
    for i in 0...allFields.count - 1 {
        DataBaseManagement.shared.deleteAllFields(inputId: i)
    }
}

func drawFields(){
    //MARK: Field All Array wiht all (properrties for field and yours parcels)
    for i in 0...allFields.count - 1{

        let arr = try! JSONSerialization.jsonObject(with: total_parcels[i]._json_Parcel.data(using: .utf8)!, options: []) as! [[Double]]
        allFields[i]._parcel.append(total_parcels[i]._json_Parcel);
        //MARK: SAVE LATITUDE AND LONGITUDE IN ARRAY
        for j in 0...arr.count - 1{
            let longitude = arr[j][0]//latitud
            let latitude = arr[j][1]//longitud

            rect.add(CLLocationCoordinate2D(latitude: latitude, longitude: longitude))
        }



        //MARK: DRAW ON THE MAP
        let polygon = GMSPolygon()
        polygon.path = rect
        poligons.append(polygon)
        rect = GMSMutablePath()
        polygon.fillColor = UIColor(red: 8/256, green: 246/255, blue: 191/255, alpha: 0.3)
        polygon.strokeColor = .blue
        polygon.strokeWidth = 2
        polygon.map = mapView


    }

    let end = NSDate()
    self.timer.stopAnimating()
    print("TIME CHARGE 'MAIN MAP'")
    print(start)
    print(end)  
}

let urlSnapshot = "..."
func getDeliverablesForField(){
    let deliverablesFacade = DeliverablesFacade()
    deliverablesFacade.snapshots(url: urlSnapshot,
                              callbackFuncionOK: snapshotsOK,
                              callbackFunctionERROR: snapshotsERROR)
}



func snapshotsOK( snapshotsResponse:  SnapshotsLegendModel) {

    snapShotsLegend = snapshotsResponse.copySnapshots()
    print("end recover fields")

}



func snapshotsERROR(_ httpCode: Int,nsError: NSError) {
    if httpCode == -1 {
        print(nsError)
        print(httpCode)
    }else{
        print(nsError)
        print(httpCode)
    }
}

var onlyOnetime = 0

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {

    for polygon in poligons{

        if (GMSGeometryContainsLocation(CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude), polygon.path!, true)) {
            onlyOnetime = onlyOnetime + 1

            if onlyOnetime == 1{
                getDeliverablesForField()
                showLegend.setValue(true, forKey: showLegendInformation)
                let bounds = GMSCoordinateBounds(path: polygon.path!)
                self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0))
                self.iconBarLegend.isEnabled = true
                self.iconBarLegend.tintColor = UIColor.black
            }

            polygon.fillColor = UIColor(red: 8/256, green: 246/255, blue: 191/255, alpha: 0.9)
            polygon.strokeColor = .blue
            polygon.strokeWidth = 2
            polygon.map = mapView

            //self.viewDidLoad()
        }

        else{
            polygon.fillColor = UIColor(red: 8/256, green: 246/255, blue: 191/255, alpha: 0.3)
            polygon.strokeColor = .blue
            polygon.strokeWidth = 2
            polygon.map = mapView
        }
    }
}



func coordinatesWFSOKERROR(_ httpCode: Int,nsError: NSError) {
    if httpCode == -1 {
        print(nsError)
        print(httpCode)
    }else{
        print(nsError)
        print(httpCode)
    }
}

@IBAction func goToAdvancedSearch(_ sender: Any) {
    let advancedSearch:  AdvancedSearchVC = UIStoryboard(name: "AdvancedSearch", bundle: nil).instantiateViewController(withIdentifier: "AdvancedSearchVC") as! AdvancedSearchVC
    self.navigationController?.pushViewController(advancedSearch, animated: false)
}

}

扩展名MainMapVC:LeftSideDelegate {

func sendShapeDelivery(deliveryPos : Int){

    if feedModelDeliveries[deliveryPos].swichtActiveLayer == true  {
        if true {
            print("Not exist deliverable -> call WMS")
            let nameDelivery = snapShotsLegend.legendEntries[0].deliverables[deliveryPos].url_layer
            let urls: GMSTileURLConstructor = { (x: UInt, y: UInt, zoom: UInt) -> URL in

                let bbox = self.layer.bboxFromXYZ(x, y: y, z: zoom)
                let urlKN = "http://192.168.0.160:8080/geoserver/LordWor/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&tiled=true&STYLES=line&layers=LordWor:\(nameDelivery)&styles=&WIDTH=256&HEIGHT=256&SRS=EPSG:3857&BBOX=\(bbox.left),\(bbox.bottom),\(bbox.right),\(bbox.top)"
                print("PETICION WMS DEL LALER: \(nameDelivery)")

                return URL(string: urlKN)!
            }

            let tileLayer: GMSURLTileLayer = GMSURLTileLayer(urlConstructor: urls)
            allDeliveries.append(tileLayer)
            tileLayer.opacity = 0.5
            tileLayer.map = self.mapView

        }else{

            let tileLayer: GMSURLTileLayer = allDeliveries[deliveryPos]
            tileLayer.opacity = 0.5
            tileLayer.map = self.mapView

        }


    }else{

        let tileLayer: GMSURLTileLayer = allDeliveries[deliveryPos]
        tileLayer.opacity = 0
        tileLayer.map = self.mapView

    }


}

}

应用程序与协议和代理进行通信。例如,当我们点击图例的swicht时,类“customCell”能够检测到事件“swichtValueChanged”并将其发送到“didSappedSwicht”委托“LeftSideViewController”,但是当我们移动滑块时“customCell” “类不能检测到事件”sliderValueChanged“并使事件关闭视图(因为左边的图例左侧是向左滑动关闭的。)

如何使其检测滑块事件而不关闭视图? 谢谢

1 个答案:

答案 0 :(得分:1)

您应该将Slider绑定到两个事件" 触发主要操作"和" 触摸内部"

这里我附上了图片供你参考

enter image description here

并删除此方法上的左滑动和右滑动手势

方法描述和代码

1"触发主要操作"

单击滑块时,该方法将调用"触发主要操作"

注意:停用手势

(UISwipeGestureRecognizerDirection.right和UISwipeGestureRecognizerDirection.left)

2 Touch Up Inside

注意:同时启用手势

(UISwipeGestureRecognizerDirection.right和UISwipeGestureRecognizerDirection.left)