在#selector函数中传递数据

时间:2017-11-09 01:34:12

标签: ios swift uibutton mapkit

在点击按钮时,我无法确定传递数据的最佳方法。我也想在点击按钮时设置动画。该按钮位于地图注释的自定义标注视图内。我尝试设置一个类属性dogIDOfUpvoteTapped,并使用它来存储数据,以便被调用的函数可以访问它。不幸的是,当我想与按钮本身进行交互时,事情会变得复杂。

如何从被调用函数'upvoteButtonTapped'获取对'CustomAnnotation'对象的引用?我省略了一堆不相关的代码,但这就是我正在使用的代码:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if view.annotation is MKUserLocation {
        return
    }

    let customAnnotation = view.annotation as! CustomAnnotation
    let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
    let calloutView = views?[0] as! CustomCalloutView

    dogIDOfUpvoteTapped = customAnnotation.dogID

    calloutView.scoreLabel.text = text
    calloutView.creatorLabel.text = customAnnotation.creator
    calloutView.dogImageView.image = customAnnotation.picture
    calloutView.upvoteButton.addTarget(self, action: #selector(upvoteTapped), for: .touchUpInside)

    view.addSubview(calloutView)
}

这是upvoteTapped的功能,虽然我在那里做的事与这个问题非常相关。

@objc func upvoteTapped() {
    let ref = Database.database().reference().child("dogs").child(dogIDOfUpvoteTapped)
    ref.child("upvotes").observeSingleEvent(of: .value, with: { (snap) in
        var currentUpvotes = Int(snap.value as! String)!
        currentUpvotes += 1
        ref.child("upvotes").setValue(String(currentUpvotes))
    })

}

1 个答案:

答案 0 :(得分:0)

@ leo-dabus说得对,你需要使用发送方式(按钮)的方法变体。

此外,将标记附加到该按钮以在集合中标识它,NB它必须是整数,并且我假设您正在使用或有权访问数据库项目列表中的整数Id或索引(dogID)

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if view.annotation is MKUserLocation {
        return
    }

    let customAnnotation = view.annotation as! CustomAnnotation
    let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
    let calloutView = views?[0] as! CustomCalloutView

    dogIDOfUpvoteTapped = customAnnotation.dogID

    calloutView.scoreLabel.text = text
    calloutView.creatorLabel.text = customAnnotation.creator
    calloutView.dogImageView.image = customAnnotation.picture
    calloutView.upvoteButton.tag = dogIDOfUpvoteTapped
    calloutView.upvoteButton.addTarget(self, action: #selector(upvoteTapped:), for: .touchUpInside)

    view.addSubview(calloutView)
}

@objc func upvoteTapped(_ button: UIButton) {
    let ref = Database.database().reference().child("dogs").child(button.tag)
    ref.child("upvotes").observeSingleEvent(of: .value, with: { (snap) in
        var currentUpvotes = Int(snap.value as! String)!
        currentUpvotes += 1
        ref.child("upvotes").setValue(String(currentUpvotes))
    })

}

没有看到customAnnotation.dogID的类,我假设它是一个整数,如果是一个字符串或其他,你需要使用一个int的主键或索引。可以肯定的是,主键是一个int。