我想在 TableView
中获取 index
所选项目并在此之后开始一些活动 . 不幸的是,我发现大多数解决方案都是客观的,或者不起作用 .
方法 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])!")
}
}
8 回答
一些需要发生的事情......
视图控制器需要扩展类型
UITableViewDelegate
视图控制器需要包含
didSelectRowAt
函数 .表视图必须将视图控制器指定为其委托 .
下面是一个可以进行分配委托的地方(在视图控制器内) .
并且
didSelectRowAt
函数的简单实现 .继承tableview委托和数据源 . 代表您需要的代表 .
最后实现这个代表
我自己使用weheartswift教程解决了问题
In Swift 3.0
您可以通过委托方法找到触摸/单击tableview单元格的事件 . 同样,可以像这样找到单元格的section和row值 .
这对我很有用:
输出应该是:
如果你想要来自单元格的值,那么你不必在
didSelectRowAtIndexPath
中重新创建单元格任务如下:
你也必须检查
cellForRowAtIndexPath
你必须设置标识符 .希望能帮助到你 .
To get an elements from Array in tableView cell touched or clicked in swift