简体   繁体   中英

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.

Image of prototype TableViewCell in Table View with two labels and an image. At the top there is the Tap Gesture Recognizer logo:

在此处输入图片说明

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.

However, on my other view that isn't a table view, I can get this to work fine. I'm new to 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.

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. One of the UILabels in the class, and the cell, is updated. 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. 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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