swift2 使用UITapGestureRecognizer传递参数

qqrboqgw  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(225)

有什么方法可以用UITapGestureRecognizer传递参数吗?我看到objective-c可以回答这个问题,但swift却找不到答案

test.userInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped4:"))
// Something like text.myParamater
test.addGestureRecognizer(tapRecognizer)

然后在函数imageTapped 4(){}下接收myParameter

tp5buhyn

tp5buhyn1#

一种方法是创建UITapGestureRecognizer的子类,然后设置一个属性,我在下面给出了一个例子。

class ViewController: UIViewController {

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var image: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        image.userInteractionEnabled = true;
        let tappy = MyTapGesture(target: self, action: #selector(self.tapped(_:)))
        image.addGestureRecognizer(tappy)
        tappy.title = "val"
    }

    func tapped(sender : MyTapGesture) {
        print(sender.title)
        label1.text = sender.title
    }
}

class MyTapGesture: UITapGestureRecognizer {
    var title = String()
}

有很多关于SO的例子,看一看,祝你好运。

ff29svar

ff29svar2#

雨燕4

在视图中已加载

let label     =   UILabel(frame: CGRect(x: 0, y: h, width: Int(self.phoneNumberView.bounds.width), height: 30))
                label.textColor = primaryColor
                label.numberOfLines = 0
                label.font = title3Font
                label.lineBreakMode = .byWordWrapping
                label.attributedText = fullString

 let phoneCall = MyTapGesture(target: self, action: #selector(self.openCall))
        phoneCall.phoneNumber = "\(res)"
            label.isUserInteractionEnabled = true
            label.addGestureRecognizer(phoneCall)

功能为

@objc func openCall(sender : MyTapGesture) {
        let number = sender.phoneNumber
        print(number)
}

将类编写为

class MyTapGesture: UITapGestureRecognizer {
    var phoneNumber = String()
}

正确执行步骤,并根据变量、按钮、标签进行更改。工作正常

woobm2wo

woobm2wo3#

如果不进行子类化,也可以在视图层(手势附加的位置)中添加参数:

let tappy = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:)))
image.addGestureRecognizer(tappy)
image.layer.setValue(title, forKey: "anyKeyName")

稍后在处理程序中

@objc private func tapped(_ sender: UIGestureRecognizer) {
    guard let title = sender.view?.layer.value(forKey: "anyKeyName") as? String else { return }
    // Do something with the title
}
lyr7nygr

lyr7nygr4#

最好的方法是在func imageTapped64被触发时确定参数。你可以通过视图(看一下@Developer谢尔顿的答案)或其他许多方式获得参数。

相关问题