creating an action when tableView cell in swift touched or clicked

吃可爱长大的小学妹 提交于 2019-12-14 04:23:01

问题


I a tableView class that displays a text in cells. I need to be able to touch/click text in a cell and create an action (display the next table view) based on the text in the cell clicked. Class is as follows:

import UIKit

class  SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!


    let textCellIdentifier = "TextCell"
    let catRet = XnYCategories.mainCats("sport")

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    // MARK:  UITextFieldDelegate Methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return catRet.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell

        let row = indexPath.row
        cell.textLabel?.text = catRet[row]
        return cell

    }

    // MARK:  UITableViewDelegate Methods
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let row = indexPath.row
        println(catRet[row])

    }
}

回答1:


I would like to add upon Linus answer, as it has deprecated in latest Swift addition.

Swift 4:

In the myCell add this Recogniser,

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(yourVC.yourfuncName))
        myCell.addGestureRecognizer(tapGesture)

In the same VC, implement your function,

func yourfuncName(){

   //Do whatever you want here

    }



回答2:


If you have a hard-coded amount of cells, you can create a UIGestureRecognizer and add it to the cell created:

let tapGesture = UITapGestureRecognizer(target: self, action: "tapped:")
myCell.addGestureRecognizer(tapGesture)

In it's target you can do whatever you want to do.




回答3:


You can get your cell using

let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell

To get your text you could use

var selectedText = currentCell.textLabel?.text


来源:https://stackoverflow.com/questions/29973506/creating-an-action-when-tableview-cell-in-swift-touched-or-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!