UITapGestureRecognizer发送者是手势,而不是ui对象

问题描述 投票:9回答:1

我有一个名为的按钮,并且给了它一个UIGestureRecognizer,以便仅在长按该按钮时才运行IBAction。您可以通过向按钮本身添加UILongPressGestureRecognizer来执行此操作。然后,您可以控制将该手势识别器拖动到如下功能:

 @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)
    }
}

您可以看到UIAlertController出现,我希望标题显示按钮的当前标题。如果此函数的发送者是按钮,则可以使用sender.currentTitle进行调用。当函数的发送者是手势时,如何获取与手势相关的按钮的标题。

我在目标C中看到过这样的帖子,但是在Swift上却一无所获。当您长按按钮本身时,这就是项目获得按钮说明的全部。

ios xcode swift uigesturerecognizer
1个回答
24
投票

您可以通过手势的view属性获得对该手势添加到的视图的引用。在这种情况下,您要将其添加到按钮,以便view属性将为您返回按钮。

let button = sender.view as? UIButton
© www.soinside.com 2019 - 2024. All rights reserved.