我是iOS开发的新手,使用xcode 8.2.1& swift 3.我在视图控制器中使用uitableview,在uitableviewcell中当我点击它时采取uiimageview应用程序崩溃并且当我按下按钮并执行按钮操作时会发生同样的问题。
错误是:
sampleToRunBuild [3752:1620857] - [sampleToRunBuild.TapViewController TappedOnImage:]:无法识别的选择器发送到实例0x141e07bc0 2017-04-13 18:18:00.531126 sampleToRunBuild [3752:1620857] * 由于未捕获的异常而终止应用程序 ' NSInvalidArgumentException',原因: ' - [sampleToRunBuild.TapViewController TappedOnImage:]:无法识别 选择器发送到实例0x141e07bc0' * 第一次抛出调用堆栈:(0x18343d1b8 0x181e7455c 0x183444268 0x183441270 0x18333a80c 0x1898b3f80 0x1898b7688 0x18947e73c 0x18931d0f0 0x1898a7680 0x1898a71e0 0x1898a649c 0x18931b30c 0x1892ebda0 0x189ad575c 0x189acf130 0x1833eab5c 0x1833ea4a4 0x1833e80a4 0x1833162b8 0x184dca198 0x1893567fc 0x189351534 0x100065f30 0x1822f95b8)libc ++ abi.dylib:以未捕获终止 NSException类型的异常
我的代码是:
import UIKit
class TapViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "mycell")
let img: UIImageView = cell?.viewWithTag(1) as! UIImageView
let img2: UIImageView = cell?.viewWithTag(2) as! UIImageView
img.tag = indexPath.row
img2.tag = indexPath.row
img.isUserInteractionEnabled = true
img2.isUserInteractionEnabled = true
let tapped:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector(("TappedOnImage:")))
tapped.numberOfTapsRequired = 1
tapped.delegate = self
img.addGestureRecognizer(tapped)
let tapped1:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector(("TappedOnImage:")))
tapped1.numberOfTapsRequired = 1
tapped1.delegate = self
img.addGestureRecognizer(tapped1)
return cell!
}
func TappedOnImage(sender:UITapGestureRecognizer){
print("tap on imageview")
}
}
提前致谢...
答案 0 :(得分:1)
添加UITapGestureRecognizer
,如下面的代码
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
// Your action
}
答案 1 :(得分:0)
你需要使用
#selector(TapViewController.imageTapped(sender:))
答案 2 :(得分:0)
如果您使用的是swift 3,请不要再使用Selector()
,请改用#selector
语法。
e.g。
let tapped1:UITapGestureRecognizer =
UITapGestureRecognizer(target: self, action: #selector(TappedOnImage))
您的代码无效的原因是您忘记将参数标签sender
添加到选择器字符串。这是使用旧语法的一个缺点 - 它不会告诉你编译时的错误。使用新语法,如果您错误地编写了选择器,则会出现编译器错误,并且您甚至不需要关心参数标签,只需要名称。