gpt4 book ai didi

ios - 将数据从 TableViewController 传递到 TableViewCell

转载 作者:行者123 更新时间:2023-11-28 05:33:17 24 4
gpt4 key购买 nike

我创建了一个 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
}

}

表格打印的很好,如下图所示:

Table View Controller

现在,每次按下“地址”按钮时,我都需要访问属性地址,您可以在图片中看到。所以我在 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 访问“地址”字段。

我可以使用什么解决方案?附言。我试图为 TableViewController 类创建一个实例:

func playActionX(sender:UIButton!) {
println(sender.tag)
let instance:MyTableViewController = MyTableViewController()
println(instance.getPeopleArray())
}

(getPeopleArray 只是返回数组 people)但奇怪的是,我收到的数组是空的,我不明白为什么。

感谢您的支持

最佳答案

您的 getPeopleArray 是空的,因为您正在创建 MyTableViewController 的新实例,而不是访问现有实例。但不要走那条路。相反,只需将按钮的目标/操作更改为 View Controller ,而不是单元格。所以改变:

cell.buttonPlay?.addTarget(cell, action: "playActionX:", forControlEvents: UIControlEvents.TouchUpInside)

cell.buttonPlay?.addTarget(self, action: "playActionX:", forControlEvents: UIControlEvents.TouchUpInside)

并将playActionX: 函数移动到 TableView Controller 。从那里您可以将标签用作人员数组的索引。

关于ios - 将数据从 TableViewController 传递到 TableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26509357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com