xcode UITapGestureRecognizer 发送者是手势,而不是 ui 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30972288/
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
UITapGestureRecognizer sender is the gesture, not the ui object
提问by modesitt
I've got a button called and I gave it a UIGestureRecognizer
so that an IBAction
is only run when the button is long pressed. You do this by adding a UILongPressGestureRecognizer
to the button iteself. Then you control drag that gesture recognizer to a function like this:
我有一个按钮被调用,我给了它一个,UIGestureRecognizer
以便IBAction
只有在长按按钮时才会运行。您可以通过向UILongPressGestureRecognizer
按钮本身添加 a来完成此操作。然后您控制将该手势识别器拖动到如下功能:
@IBAction func handleGesture(sender: UIGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began
{
let labelTap1=UITapGestureRecognizer(target: self, action: "labelTapped:")
let alertController = UIAlertController(title: "**I want this to be the title of the button**", message:
"This is the description of the function you pressed", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
As you can see the UIAlertController
appears, I want the title to show the buttons current title. If the sender of this function was the button, I could call this with sender.currentTitle
. How can I get the title of the button that is tied to the gesture, when the sender of the function is the gesture.
如您所见UIAlertController
,我希望标题显示按钮的当前标题。如果这个函数的发送者是按钮,我可以用sender.currentTitle
. 当功能的发送者是手势时,如何获得与手势绑定的按钮的标题。
I have seen posts like this in objective C, but nothing really on Swift. This is all for a project to get a buttons description when you longpress on the button itself.
我在目标 C 中看到过这样的帖子,但在 Swift 上没有任何内容。当您长按按钮本身时,这就是项目获取按钮描述的全部内容。
回答by Kris Gellci
You can get a reference to the view the gesture is added to via its view property. In this case you are adding it to the button so the view property would return you you the button.
您可以通过其 view 属性获取对添加手势的视图的引用。在这种情况下,您将其添加到按钮中,以便视图属性将按钮返回给您。
let button = sender.view as? UIButton