如何向UITapGestureRecognizer添加参数,以便操作功能可以访问该参数

时间:2018-08-06 11:15:12

标签: ios swift uitapgesturerecognizer

我已经基于我存储在UserDefaults中的项目数量以编程方式创建了UIViews,每个UIView代表了userDefaults中的一个项目,并在其顶部添加了UITapGestureRecognizer。现在,当单击此UIViews时,会将用户发送到新的视图控制器,现在的问题是如何传递一个包含值的参数,以便新的视图控制器可以确定单击了哪个视图。下面是我的代码

//Retrieving my userDefaults values
let items = preferences.object(forKey: selectedOffer)

//How i loop and create my UIViews
if let array = items as! NSArray?{
                    totalOffers = array.count
                    let castTotalOffers = CGFloat(totalOffers)
                    var topAnchorConstraint: CGFloat = 170
                    var cardHeight: CGFloat = 145
                    for obj in array {
                        if let dict = obj as? NSDictionary{
                            offerName = dict.value(forKey: "NAME") as! String
                            let offerPrice = dict.value(forKey: "PRICE") as! String
                            let offerDescription = dict.value(forKey: "DESCRIPTION") as! String

                            //creating the uiview
                            let offerView = UIView()
                            self.scrollView.addSubview(offerView)
                            offerView.translatesAutoresizingMaskIntoConstraints = false
                            offerView.topAnchor.constraint(equalTo: self.appBackImage.bottomAnchor, constant: topAnchorConstraint).isActive = true
                            offerView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20.0).isActive = true
                            offerView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20.0).isActive = true
                            offerView.backgroundColor = UIColor.white
                            offerView.heightAnchor.constraint(equalToConstant: 130).isActive = true
                            //transforming to cards
                            offerView.layer.cornerRadius = 2
                            offerView.layer.shadowOffset = CGSize(width: 0, height: 5)
                            offerView.layer.shadowColor = UIColor.black.cgColor
                            offerView.layer.shadowOpacity = 0.1

                            self.scrollView.contentSize.height = CGFloat(totalOffers) + topAnchorConstraint + 70


                            //Adding gesture
                            let touchRec = UITapGestureRecognizer(target: self, action: #selector(goToBuyBundle(offerClicked:offerName)))
                            offerView.addGestureRecognizer(touchRec)


                        }
                    }
                }

//Function to go to buy offer
    @objc func goToBuyBundle(_sender: UITapGestureRecognizer, offerClicked:String){
        guard let moveTo = storyboard?.instantiateViewController(withIdentifier: "BuyOfferViewController") as? BuyOfferViewController else {return}
        moveTo.selectedOffer = offerClicked
        self.addChildViewController(moveTo)
        moveTo.view.frame = self.view.frame
        self.view.addSubview(moveTo.view)
        moveTo.didMove(toParentViewController: self)
    }

当我导航到下一个视图控制器时,只需要一种方法,就可以使用offerName检索单击哪个UIView。 在此先感谢

2 个答案:

答案 0 :(得分:0)

创建自定义视图,并将要通过手势识别器传递的参数存储在视图内。

class GestureView: UIView{

var myViewValue: String? // Or whichever type of value you want to store and send via the gesture
}

启动视图时,请根据需要添加值:

    let panReceptor = GestureView()
    panReceptor.myViewValue = "Hello World"

在此自定义视图上添加一个简单的TapGesture,您可以按如下所示传递值:

let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(viewTapped(sender:)))
    panReceptor.addGestureRecognizer(tapGesture)


@objc func viewTapped(sender: UITapGestureRecognizer){

    guard let unwrappedView = sender.view as? GestureView else { return }
    print("Gesture View value : \(unwrappedView.myViewValue)")
}

在上面的示例中,我实际上通过sender.view传递了一个String参数。

您可以通过这种方式传递任何类型,并根据选择器方法中的要求使用该值。

答案 1 :(得分:0)

您可以向UITapGestureRecognizer添加自定义变量,例如:

import UIKit
private var assocKey : UInt8 = 0

extension UITapGestureRecognizer {

public var offerName:String{
    get{
        return objc_getAssociatedObject(self, &assocKey) as! String

    }
    set(newValue){
        objc_setAssociatedObject(self, &assocKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
    }
}
}

然后像这样使用它:

...
let touchRec = UITapGestureRecognizer(target: self, action: #selector(goToBuyBundle(offerClicked:offerName)))
touchRec.offerName = offerName
offerView.addGestureRecognizer(touchRec)
...

 @objc func goToBuyBundle(_sender: UITapGestureRecognizer, offerClicked:String){
    guard let moveTo = storyboard?.instantiateViewController(withIdentifier: "BuyOfferViewController") as? BuyOfferViewController else {return}
    moveTo.selectedOffer = sender.offerName
...
}