Search code examples
swiftuitapgesturerecognizer

swift uitapgesturerecognizer pass parameters


I have a lot of Buttons created programmatically and that can change anytime. my tap gesture :

let apriVideoGesture = UITapGestureRecognizer(target: self, action: #selector(PrincipaleController.apriVideo(_:)))
cont.addGestureRecognizer(apriVideoGesture)

func apriVideo(sender : UITapGestureRecognizer){

}

how can i pass parameters? somethig like this :

let apriVideoGesture = UITapGestureRecognizer(target: self, action: #selector(PrincipaleController.apriVideo(stringa : "ciao")))
cont.addGestureRecognizer(apriVideoGesture)

func apriVideo(sender : UITapGestureRecognizer, stringa : String){

}

sorry for bad english, i'm italian


Solution

  • First of all, if you are using button then why are you adding tap gesture? You can add target to it as

    btn.addTarget(self, action: #selector(self.btnPressed(_:)), forControlEvents: .TouchDragInside)
    

    But still you can achieve you goal using tap gesture as

    Using UIView as u have insisted

        class ViewController: UIViewController {
    
        let arrayOfSongsURL: [String] = []
        let startingTag = 100
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let height : CGFloat = 100
            let width : CGFloat = 100
            (arrayOfSongsURL as NSArray).enumerateObjectsUsingBlock { (url, index, finished) -> Void in
                
                let v = UIView(frame: CGRectMake(0, CGFloat(index) * height, width, height))
                v.tag = self.startingTag + index
                
                v.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleTapGesture(_:))))
                self.view.addSubview(v)
            }
            // Do any additional setup after loading the view, typically from a nib.
        }
        
        
        @objc func handleTapGesture(gesture : UITapGestureRecognizer)
        {
            let v = gesture.view!
            let tag = v.tag
            let songURL = arrayOfSongsURL[tag - startingTag]
            
            //Do what you want to do with songURL
        }
    }