我试图获取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])!")
}
}