在 Swift 中如何检测 UITableView 的单元格被触摸或点击

82

我试图获取TableView中所选项目的index并在此之后启动某些活动。不幸的是,我找到的大多数解决方案都是以Objective-C编写的或者无法使用。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)方法不会打印cell标签。

有人能帮帮我吗?

import UIKit
import ResearchKit

class TaskListViewController: UIViewController, UITableViewDataSource {
    
    let tasks=[("Short walk"),
        ("Audiometry"),
        ("Finger tapping"),
        ("Reaction time"),
        ("Spatial span memory")
    ]
    
    
    //how many sections are in your table
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    //return int how many rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }
    
    //what are the contents
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        
        var (testName) = tasks[indexPath.row]
        cell.textLabel?.text=testName
        return cell
    }
    
    // give each table section a name
    
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return "Tasks"
        
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let indexPath = tableView.indexPathForSelectedRow();
        
        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
        
        println(currentCell.textLabel!.text)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }  
}

尝试了几次后,我从教程中找到了另一个代码并进行了更改。但它仍然无法运行。现在我认为这可能是iOS模拟器的问题...

import UIKit
import ResearchKit

class TaskListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet
    var tableView: UITableView?
    var items: [String] = ["We", "Heart", "Swift"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView!.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
        
        cell.textLabel?.text = self.items[indexPath.row]
        
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("You selected cell #\(items[indexPath.row])!")
    }
    
}

9个回答

88

如果你想要获取单元格的值,那么你不需要在didSelectRowAtIndexPath中重新创建单元格。

Translated text:

如果您想要从单元格中获取值,则无需在didSelectRowAtIndexPath中重新创建单元格。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(tasks[indexPath.row])
}

任务如下:

let tasks=["Short walk",
    "Audiometry",
    "Finger tapping",
    "Reaction time",
    "Spatial span memory"
]

同时,您需要检查cellForRowAtIndexPath并设置标识符。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    var (testName) = tasks[indexPath.row]
    cell.textLabel?.text=testName
    return cell
}

希望对你有所帮助。


45

在 Swift 3.0 中

通过委托方法,您可以找到表格视图单元格的触摸/点击事件。同时,可以像这样找到单元格的部分和行值。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       print("section: \(indexPath.section)")
       print("row: \(indexPath.row)")
}

16

需要完成以下几件事情:

  1. 视图控制器需要扩展类型UITableViewDelegate

  2. 视图控制器需要包括didSelectRowAt函数。

  3. 表视图必须将视图控制器分配为其委托。


以下是一个指定委托的位置(在视图控制器内)。

override func loadView() {
    tableView.dataSource = self
    tableView.delegate = self
    view = tableView
}

以下是didSelectRowAt函数的简单实现。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("row: \(indexPath.row)")
}

11

6
所选答案是否真正解决了问题?如果没有解决问题,请在您的答案中编写一个解决方案或选择适当的答案来修复您提出的问题。仅仅因为有人提供帮助和可能的解决方案,并不意味着他们的答案应被选为正确的答案。请进行修正。 - Devbot10

8

这对我很有效:

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("section: \(indexPath.section)")
        print("row: \(indexPath.row)")
    }

输出应该是:
section: 0
row: 0

6
你的回答看起来是重复的,因为它与上面的回答非常相似。https://dev59.com/AF0Z5IYBdhLWcg3wrR8r#41583381 - jdev

7
继承tableview的代理和数据源。实现你需要的代理方法。
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

最后实现这个委托。
     func tableView(_ tableView: UITableView, didSelectRowAt  
     indexPath: IndexPath) {
     print("row selected : \(indexPath.row)")
  }

4
从Swift中的tableView单元格中获取Array中的元素,当它被触摸或点击时。
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    cell.textLabel?.text= arr_AsianCountries[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexpath = arr_AsianCountries[indexPath.row]
print("indexpath:\(indexpath)")
}

3
 # Check delegate? first must be connected owner of view controller

    # Simple implementation of the didSelectRowAt function.

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         print("row selection: \(indexPath.row)")
    }

2

我每次都搞砸了!只需确保在 viewDidLoad 中声明 tableView 的代理和数据源。然后,我通常会填充一些数组来模拟返回的数据,然后就可以继续操作了!

//******** Populate Table with data ***********
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SetupCellView
    cell?.ControllerLbl.text = ViewContHeading[indexPath.row]
    cell?.DetailLbl.text = ViewContDetail[indexPath.row]
    cell?.StartupImageImg.image = UIImage(named: ViewContImages[indexPath.row])
    return cell!
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接