我正在尝试为生成的图像添加一个点击手势,它可以正常工作但是一旦我点击图像就会一直崩溃程序。我在这里做错了什么任何帮助表示赞赏。
let tapGesture = UITapGestureRecognizer(target: self, action: "image Tapped")
let imageView = UIImageView(image: UIImage(data: data));
imageView.addGestureRecognizer(tapGesture)
imageView.userInteractionEnabled = true
这是我得到的错误
2016-07-12 09:19:30.241 XXX[2170:27661] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ‘-[MyViewController image Tapped]: unrecognized selector sent to instance 0x7fe811e30560'
*** First throw call stack:
(
0 CoreFoundation 0x000000010e2a7d85 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000011144ddeb objc_exception_throw + 48
2 CoreFoundation 0x000000010e2b0d3d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010e1f6cfa ___forwarding___ + 970
4 CoreFoundation 0x000000010e1f68a8 _CF_forwarding_prep_0 + 120
5 UIKit 0x0000000110391b28 _UIGestureRecognizerSendTargetActions + 153
6 UIKit 0x000000011038e19a _UIGestureRecognizerSendActions + 162
7 UIKit 0x000000011038c197 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 843
8 UIKit 0x0000000110394655 ___UIGestureRecognizerUpdate_block_invoke898 + 79
9 UIKit 0x00000001103944f3 _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 342
10 UIKit 0x0000000110381e75 _UIGestureRecognizerUpdate + 2634
11 UIKit 0x000000010ff0e48e -[UIWindow _sendGesturesForEvent:] + 1137
12 UIKit 0x000000010ff0f6c4 -[UIWindow sendEvent:] + 849
13 UIKit 0x000000010febadc6 -[UIApplication sendEvent:] + 263
14 UIKit 0x000000010fe94553 _UIApplicationHandleEventQueue + 6660
15 CoreFoundation 0x000000010e1cd301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
16 CoreFoundation 0x000000010e1c322c __CFRunLoopDoSources0 + 556
17 CoreFoundation 0x000000010e1c26e3 __CFRunLoopRun + 867
18 CoreFoundation 0x000000010e1c20f8 CFRunLoopRunSpecific + 488
19 GraphicsServices 0x0000000112d68ad2 GSEventRunModal + 161
20 UIKit 0x000000010fe99f09 UIApplicationMain + 171
21 ApivitaClient 0x000000010d6a1482 main + 114
22 libdyld.dylib 0x0000000111f1192d start + 1
23 ??? 0x0000000000000001 0x0 + 1
) libc ++ abi.dylib:以NSException类型的未捕获异常终止 (lldb)
答案 0 :(得分:2)
替换
let tapGesture = UITapGestureRecognizer(target: self, action: "image Tapped")
与
let tapGesture = UITapGestureRecognizer(target:self, action: #selector(imageTapped))
并创建func imageTapped() {}
答案 1 :(得分:1)
UITapGestureRecognizer初始化程序中的操作部分表示将执行哪个方法。行动部分意味着谁负责该行动,谁是代表。
使用此选项初始化手势识别器:
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped:"))
请注意方法名称后面的冒号:
(imageTapped
)。这意味着手势识别器将调用imageTapped
方法并传递sender参数,如果您想确定触发了哪个手势识别器,这将非常有用。如果你有几个可以点击的图像,这非常有用,所以你不必为每个图像构建一个方法。
然后你需要声明imageTapped
方法:
func imageTapped(sender: UIGestureRecognizer) {
print("Image tapped")
}
您可以声明函数在没有参数的情况下工作,只需声明不带sender参数的函数,并删除动作选择器中的冒号。无论如何,我建议保留它,它可能在某个地方有用,如果你这样学习它会更好。