swift uitapgesturerecognizer pass parameters

Alessandro Zago picture Alessandro Zago · Jul 4, 2016 · Viewed 15.4k times · Source

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

Answer

Amit Singh picture Amit Singh · Jul 4, 2016

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] = [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.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


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
}

}