【发布时间】:2014-10-22 22:28:58
【问题描述】:
我创建了一个 TableViewController 并显示了一些来自数组的数据。 我还必须创建一个 TableViewCellController,因为我需要为每一行设置一个按钮,该按钮必须执行一个操作。
所以,这是我的 TableViewController 的一部分:
struct person {
var name:String
var age:String
var address:String
}
class myTableViewController: UITableViewController {
var people = Array<person>()
override func viewDidLoad() {
super.viewDidLoad()
var x = person(name: "Marco", age: "28", address: "street a")
var y = person(name: "Pippo", age: "90", address: "street b")
people.append(x)
people.append(y)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> myTableViewCell {
let CellId: String = "Cell"
var cell: myTableViewCell = tableView.dequeueReusableCellWithIdentifier(CellId) as myTableViewCell
cell.textLabel!.text = people[indexPath.row].name
return cell
}
}
如下图所示,表格打印良好:
现在,我每次按下您可以在图片中看到的“地址”按钮时都需要访问房产地址。 所以我尝试在 TableViewController 类中使用以下代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> myTableViewCell {
let CellId: String = "Cell"
var cell: myTableViewCell = tableView.dequeueReusableCellWithIdentifier(CellId) as myTableViewCell
cell.textLabel!.text = people[indexPath.row].name
cell.buttonPlay?.tag = indexPath.row
cell.buttonPlay?.addTarget(cell, action: "playActionX:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
并且,我从 TableViewCell 正确接收到标签:
class TableViewCell: UITableViewCell {
func playActionX(sender:UIButton!) {
println(sender.tag)
}
一切都好。但问题是,我无法在标签内发送字符串,也不知道如何从 TableViewController 访问“地址”字段。
我可以使用什么解决方案? PS。我试图为 TableViewController 类创建一个实例:
func playActionX(sender:UIButton!) {
println(sender.tag)
let instance:MyTableViewController = MyTableViewController()
println(instance.getPeopleArray())
}
(getPeopleArray 只是返回数组 people) 但奇怪的是我收到的数组是空的,我不明白为什么。
感谢您的支持
【问题讨论】:
标签: ios uitableview swift parameter-passing