简体   繁体   English

将Tap手势识别器添加到TableViewCell.swift

[英]Adding a Tap Gesture Recognizer to TableViewCell.swift

I have a table view cell with an image that I have attached a Tap Gesture Recognizer to. 我有一个表格视图单元格,其中带有一个图像,该图像已附加了Tap Gesture Recognizer。

Image of prototype TableViewCell in Table View with two labels and an image. 表视图中原型TableViewCell的图像,带有两个标签和一个图像。 At the top there is the Tap Gesture Recognizer logo: 顶部是Tap Gesture Recognizer徽标:

在此处输入图片说明

When I attempt to ctrl and drag the Tap Gesture Recognizer to the TableViewCellController , TableViewCell files or any other file, it won't let me. 当我尝试ctrl并将Tap Gesture Recognizer拖动到TableViewCellControllerTableViewCell文件或任何其他文件时,它不会让我使用。

However, on my other view that isn't a table view, I can get this to work fine. 但是,在不是表视图的其他视图上,我可以使其正常运行。 I'm new to Swift. 我是Swift的新手。 Would anyone know why this is happening, and what I can do to help it (I know I could use a button instead, but I wouldn't learn anything from that)? 有谁知道这是为什么发生的,以及我可以做些什么来帮助它(我知道我可以改用按钮,但是我从中学不到任何东西)?

Both the TableViewCell and TableViewCellController files have their default code. TableViewCellTableViewCellController文件都有其默认代码。

Edit : What I want is for the user to be able to tap the image to add +1 to a Int property in the class in the table cell. 编辑 :我想要的是用户能够点击图像以将+1添加到表单元格中的类的Int属性。 One of the UILabels in the class, and the cell, is updated. 类和单元中的UILabel之一已更新。 This is the kind of behaviour I can achieve without problem in a regular view and want to achieve in the table view. 我可以在常规视图中毫无问题地实现这种行为,并且希望在表视图中实现。

For UITableViewCell you cannot add a UITapgesture to it via storyboard because it is just a prototype cell unlike others. 对于UITableViewCell您无法通过情节UITapgesture向其添加UITapgesture ,因为它只是一个原型单元,与其他单元格不同。 If you really want to do that you can do it programatically in the delegate like this: 如果您确实想这样做,可以在委托中以编程方式进行,如下所示:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    let tapGesture = UITapGestureRecognizer(target: self, action: "SomeMethod")
    cell.myImageView.addGestureRecognizer(tapGesture)

    return cell
}

But i can't find out why you want to do that. 但是我找不到你为什么要这么做。 If you just want to do something or call some function when cell is tapped, you should be using the didSelectRowAtIndexPath . 如果您只想在点击单元格时执行某项操作或调用某些函数,则应使用didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("cell at #\(indexPath.row) is selected!")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM