我试图在TableView中获取所选项目的索引,然后启动一些活动.不幸的是,我发现的大多数解决方案都是客观的c或者不工作.
方法func tableView(tableView:UITableView,didSelectRowAtIndexPath indexPath:NSIndexPath)不打印单元格标签..
有人可以帮我吗
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])!")
}
}
解决方法
如果要从单元格中获取值,则不必在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
}
希望它有帮助.