[英]Passing data from TableViewController to TableViewCell
我創建了一個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只是返回數組的人),但奇怪的是我收到的數組是空的,我不明白為什么。
謝謝你的支持
由於正在創建MyTableViewController的新實例,而不訪問現有實例,因此getPeopleArray
為空。 但是不要走那條路。 相反,只需更改按鈕的目標/操作即可,而不是更改單元格。 所以改變:
cell.buttonPlay?.addTarget(cell, action: "playActionX:", forControlEvents: UIControlEvents.TouchUpInside)
至
cell.buttonPlay?.addTarget(self, action: "playActionX:", forControlEvents: UIControlEvents.TouchUpInside)
並將playActionX:
函數移至表格視圖控制器。 從那里,您可以將標簽用作進入人員數組的索引。
由於設置了tag = indexPath.row
,因此可以像在cellFoRowAtIndexPath
一樣找到地址,即people[sender.tag].address
。
嘗試將數組發現為空的原因是,您已經分配了一個新數組以及新的視圖控制器。
只要您在cellForRowAtIndexPath
中分配按鈕標簽,就應該能夠使用people[sender.tag]
(在playActionX
內部playActionX
)訪問people數組中的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.