ios 在 Swift 中使用 UITapGestureRecognizer 中的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32085396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:19:24  来源:igfitidea点击:

Using parameters in action of UITapGestureRecognizer in Swift

iosswiftswift2

提问by Cherryholme

I am trying to call a function with parameters using the action of UITapGestureRecognizerand I can't figure out any alternative.

我正在尝试使用 的操作调用带有参数的函数,但UITapGestureRecognizer我想不出任何替代方法。

This here is the gesture that is suppose to call the doubleTap function with the indexPathparameter.

这是假设使用indexPath参数调用 doubleTap 函数的手势。

var gestureDoubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "doubleTap(indexPath)")

This here is the function that is suppose to be called.

这是假设要调用的函数。

func doubleTap(indexPath: NSIndexPath) {
    NSLog("double tap")
    NSLog("%@", indexPath.row)
}

How can I call the doubleTapfunction with the indexPathparameter?

如何doubleTap使用indexPath参数调用函数?

Thank you for all suggestions.

谢谢你的所有建议。

EDIT- this is my whole code, it is basically setting up the object 'name' so my second viewController can get it and use it

编辑- 这是我的全部代码,它基本上是设置对象“名称”,以便我的第二个 viewController 可以获取并使用它

import UIKit
class viewController1: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    var imageArray:[String] = []
    var name : AnyObject? {
        get {
        return NSUserDefaults.standardUserDefaults().objectForKey("name")
        }
        set {
            NSUserDefaults.standardUserDefaults().setObject(newValue!, forKey: "name")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as myViewCell

        //adding single and double tap gestures for each cell
        /////////////////////////////
        //ISSUE IS SENDING indexPath TO doubleTap FUNC
        var gestureDoubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "doubleTap:")
        gestureDoubleTap.numberOfTapsRequired = 2
        cell.addGestureRecognizer(gestureDoubleTap)

        var gestureSingleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "singleTap")
        gestureSingleTap.numberOfTapsRequired = 1
        cell.addGestureRecognizer(gestureSingleTap)

        cell.imgView.image=UIImage(named: imageArray[indexPath.row])        
        return cell
    }

    //func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
    //
    //    name = imageArray[indexPath.row]
    //}

    override func viewDidLoad(){
        super.viewDidLoad()
        imageArray=["1.png","2.png","2.png","1.png","1.png","2.png","1.png","2.png","1.png","2.png","1.png","2.png","1.png","2.png","1.png","2.png"]

    }

    func doubleTap(sender: UITapGestureRecognizer) {
        var tapLocation = sender.locationInView(self.collectionView)

        var indexPath:NSIndexPath = self.collectionView.indexPathForItemAtPoint(tapLocation)!

        //var cell = self.collectionView.cellForItemAtIndexPath(indexPath)

        NSLog("double tap")
        NSLog("%@", indexPath)

        //NSLog("%@", cell!)
        //THIS IS THE GOAL----- set 'name' with the appropriate img      corresponding the cell
        //name = imageArray[indexPath]
        //self.performSegueWithIdentifier("segue", sender: nil)
    }

    func singleTap() {
        NSLog("single tap")
    }
}

回答by Unheilig

Given that you have NSIndexPath, I suppose you would like to retrieve the corresponding indexPathfrom the tap touch point on your UITableView.

鉴于你有NSIndexPath,我想你想indexPath从你的UITableView.

UIGestureRecognizerhas one (or no) parameter. When there is one provided, it passes itself - the indexPathis, however, notpassed to the function as mentioned.

UIGestureRecognizer有一个(或没有)参数。当提供了一个时,它会传递自己 -indexPath但是,没有传递给提到的函数。

Let's say we have the following:

假设我们有以下内容:

let aTap = UITapGestureRecognizer(target: self, action: "tapped:")

and the corresponding function when the view is tapped on:

以及点击视图时的相应功能:

func tapped(sender: UITapGestureRecognizer)
{
    //using sender, we can get the point in respect to the table view
    let tapLocation = sender.locationInView(self.tableView)

    //using the tapLocation, we retrieve the corresponding indexPath
    let indexPath = self.tableView.indexPathForRowAtPoint(tapLocation)

    //finally, we print out the value
    print(indexPath)

    //we could even get the cell from the index, too
    let cell = self.tableView.cellForRowAtIndexPath(indexPath!)

    cell.textLabel?.text = "Hello, Cell!"
 }

Update:

更新:

This serves to show how to add a gesture recognizer to the view, through which we retrieve the indexPathof the cell(item) that was tapped on twice.

这用于展示如何向视图添加手势识别器,通过它我们检索被点击两次indexPathcell( item) 的 。

The callback function is triggered, within which we could check whether or not the cell(item) that was tapped on is the one we are interested in.

回调函数被触发,我们可以在其中检查被点击的cell( item)是否是我们感兴趣的。

override func viewDidLoad()
{
    super.viewDidLoad()

    let doubleTaps = UITapGestureRecognizer(target: self, action: "doubleTapTriggered:")
    doubleTaps.numberOfTapsRequired = 2
    self.view.addGestureRecognizer(doubleTaps)
}

func doubleTapTriggered(sender : UITapGestureRecognizer)
{
    var tapLocation = sender.locationInView(self.collectionView)
    var indexPath : NSIndexPath = self.collectionView.indexPathForItemAtPoint(tapLocation)!

    if let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
    {
        if(cell.tag == 100)
        {
            print("Hello, I am cell with tag 100")
        }
        else if(cell.tag == 99)
        {
            print("Hello, I am cell with tag 99")
            //We could do something, then, with the cell that we are interested in.
            //I.e., cell.contentView.addSubview(....)
        }
    }
}

Another Update:

另一个更新:

Since it appears that you are adding gesture recognizer that requires double taps to all cells, which tells me that you are interested in any cell that was double-tapped on; and so, we would't need any condition to check whether or not the cells are the ones we are interested in, because they all are.

由于您似乎正在添加需要双击所有单元格的手势识别器,这告诉我您对双击的任何单元格感兴趣;因此,我们不需要任何条件来检查这些单元格是否是我们感兴趣的单元格,因为它们都是。

And so:

所以:

func doubleTapTriggered(sender : UITapGestureRecognizer)
{
    var tapLocation = sender.locationInView(self.collectionView)
    var indexPath : NSIndexPath = self.collectionView.indexPathForItemAtPoint(tapLocation)!

    name = imageArray[indexPath]
    self.performSegueWithIdentifier("segue", sender: nil)
}

回答by Uriel

The Best way to achieve what you wish is get the superview of your tap gesture, this will give you the correct indexPath. Try this:

实现您的愿望的最佳方法是获取点击手势的超级视图,这将为您提供正确的 indexPath。尝试这个:

   func doubleTap(sender: UITapGestureRecognizer) {
        let point = sender.view
        let mainCell = point?.superview
        let main = mainCell?.superview
        let cell: myViewCell = main as! myViewCell
        let indexPath = collectionView.indexPathForCell(cell)
    }

You can increase or reduce the superview's depending on you hierarchy level.

您可以根据层次结构级别增加或减少超级视图。

回答by user2277872

All you need to do is call it without using any kind of parameters in your string literal.

您需要做的就是在不使用字符串文字中的任何类型的参数的情况下调用它。

var gestureDoubleTap = UITapGestureRecognizer(target: self, action: "doubleTap:")

The :tells the computer that you're using a function with a parameter, and that is created somewhere else.

:告诉您使用带有参数的函数的计算机,并创建其他地方。

Hope this helps :)

希望这可以帮助 :)

回答by Vikas Dadheech

As described in apple developer documents, the action parameter should receive

如苹果开发者文档中所述,action 参数应接收

action::-A selector that identifies the method implemented by the target to handle the gesture recognized by the receiver. The action selector must conform to the signature described in the class overview. NULL is not a valid value.

action::-一个选择器,用于标识目标实现的方法来处理接收器识别的手势。动作选择器必须符合类概述中描述的签名。NULL 不是有效值。

And Valid action method signatures described in UIGestureRecognizer.h are:

UIGestureRecognizer.h 中描述的有效操作方法签名是:

// -(void)handleGesture; // -(void)handleGesture:(UIGestureRecognizer*)gestureRecognizer;

// -(void)handleGesture; // -(void)handleGesture:(UIGestureRecognizer*)gestureRecognizer;

So basically, you will notbe able to send anything else as the parameter except the gestureRecognizer.

所以基本上,除了gestureRecognizer 之外,您将无法发送任何其他参数作为参数。