【问题标题】:UITapGestureRecognizer called immediately立即调用 UITapGestureRecognizer
【发布时间】:2023-03-31 04:10:01
【问题描述】:

我正在尝试将UITapGestureRecognizer 添加到imageview,如下所示

let gest=UITapGestureRecognizer(target: self, action: Selector(imgPressed()));
gest.delegate=self
thalaImg.addGestureRecognizer(gest)

这里是imgPressed 函数:

func imgPressed()
{ 
    let alert=UIAlertController(title: "Img", message: "img pressed", preferredStyle: .Alert) 
    let okButton=UIAlertAction(title: "Ok", style: .Default, handler: nil) 
    alert.addAction(okButton) 
    presentViewController(alert, animated: true, completion: nil) 
}

我在viewdidload 中添加了 3 行代码,添加了断点并运行了应用程序。我观察到,一旦编译器到达第一行,即 let gest...,它会立即调用 action 方法甚至在应用程序开始运行之前。由于显然 window 尚未加载,它会引发以下警告

警告:尝试呈现不在窗口层次结构中的视图!

我不明白为什么会这样。有人可以帮我解决这个问题吗?

谢谢

【问题讨论】:

  • 'func imgPressed() { let alert=UIAlertController(title: "Img", message: "img pressed", preferredStyle: .Alert) let okButton=UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(okButton) presentViewController(alert, animated: true, completion: nil) }'
  • 好的,在 imgPressed 方法之后删除 ()。并在双引号中加上“imgPressed”。
  • 您正在研究哪个 swift 版本意味着 swift 2.0 或 swift 3.0?
  • 你已经把方法绑定到手势识别器了对吧?

标签: ios xcode swift uigesturerecognizer uitapgesturerecognizer


【解决方案1】:

您应该使用以下语法:

let gest = UITapGestureRecognizer(target: self, action: #selector(imgPressed))

注意,Selector 可以接受初始类型 Void 以及 String。正确的旧式Selector 初始化如下所示:

let action: Selector = Selector("imgPressed")

现在你可以检查一下,如果你尝试将新样式与旧样式结合起来,你会得到编译错误:

let action = Selector(imgPressed) // Error!

有趣的是,您可能会尝试通过附加括号来解决此错误,之后您将不会有任何错误!但这完全没用。看下面3行代码,它们是等价的

let action = Selector(imgPressed())
let action = Selector(Void())
let action = Selector()

除了一件事 - 在第一行中,您调用了 imgPressed() 函数,并通过您的双手返回了 Void。就是这样=)

【讨论】:

    【解决方案2】:

    更改您的手势线,如下所示如果 swift 2.0 或更低版本

    let gest=UITapGestureRecognizer(target: self, action: Selector("imgPressed"));
    

    如果您使用的是 swift 2.2 或更高版本

    let gest=UITapGestureRecognizer(target: self, action: #selector(imgPressed));
    

    希望这会对你有所帮助。

    【讨论】:

    • 好吧,我将 ** Selector(imgPressed()) ** 更改为 #selector(imgPressed)。立即调用方法的问题已解决,但现在当我点击图像时没有调用该方法
    • @koushikv 确保您的UIImageView 中的userInteractionEnabled 属性设置为true。在viewDidLoad中添加thalaImg.userInteractionEnabled = true
    • 您需要将 userInterActionEnabled 设置为 true
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多