OGeek|极客世界-中国程序员成长平台

标题: ios - 在#selector 函数中传递数据 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:15
标题: ios - 在#selector 函数中传递数据

我无法确定点击按钮时传递数据的最佳方式。我还想在点击按钮时为其设置动画。该按钮位于 map 注释的自定义标注 View 内。我尝试设置一个类属性 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))
    })

}



Best Answer-推荐答案


@leo-dabus 说得对,因为您需要将方法的变体与发件人(按钮)一起使用。

另外,将标签附加到该按钮以在集合中识别它,注意它必须是整数,我假设您正在使用或有权访问数据库项目列表中的整数 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。

关于ios - 在#selector 函数中传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47192485/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4