触摸或单击swift中的tableView单元格时创建操作

时间:2015-04-30 16:50:52

标签: swift tableview cell

我是一个在单元格中显示文本的tableView类。我需要能够触摸/单击单元格中的文本,并根据单击的单元格中的文本创建操作(显示下一个表格视图)。课程如下:

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])

    }
}

3 个答案:

答案 0 :(得分:1)

我想补充一下Linus的答案,因为它在最新的Swift中已被弃用。

Swift 4:

在myCell中添加此识别器,

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

在同一个VC中,实现你的功能,

func yourfuncName(){

   //Do whatever you want here

    }

答案 1 :(得分:0)

您可以使用

获取您的手机
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell

要获取文字,您可以使用

var selectedText = currentCell.textLabel?.text

答案 2 :(得分:0)

如果你有一个硬编码的单元格数量,你可以创建一个UIGestureRecognizer并将其添加到创建的单元格中:

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

在它的目标中,你可以做任何你想做的事。

相关问题