gpt4 book ai didi

ios - 如何从 TableView 中自定义单元格中的标签获取文本

转载 作者:行者123 更新时间:2023-11-28 06:36:13 27 4
gpt4 key购买 nike

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = self.tbl_vw.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as!cuscellTableViewCell

cell.txt_lbl.text = self.section[indexPath.row];
cell.sel_btn.addTarget(self, action: #selector(self.switchChanged), forControlEvents: .ValueChanged)

return cell

}



func switchChanged(sender: AnyObject) {
let switchControl: UISwitch = sender as! UISwitch
print("The switch is \(switchControl.on ? "ON" : "OFF")")

if switchControl.on {
print("The switch is on lets martch")
}
}

我在表格 View 的自定义单元格中有一个开关和一个标签。当我打开开关时,我需要获取标签中的文本,任何人都可以帮助实现这一点。

最佳答案

使用 UISwitch 的标签属性来存储位置,并在您的处理程序中使用它来获取实际的文本表单部分数组。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = self.tbl_vw.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as!cuscellTableViewCell

cell.txt_lbl.text = self.section[indexPath.row];

cell.sel_btn.tag = indexPath.row

cell.sel_btn.addTarget(self, action: #selector(self.switchChanged), forControlEvents: .ValueChanged)

return cell

}



func switchChanged(sender: AnyObject)
{
let switchControl: UISwitch = sender as! UISwitch
print("The switch is \(switchControl.on ? "ON" : "OFF")")

let text = self.section[switchControl.tag]
print(text)

if switchControl.on
{
print("The switch is on lets martch")
}
}

如果您有多个包含多行的部分,您可以使用字典并存储一个元组。

var items = [Int:(Int,Int)]()
...

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = self.tbl_vw.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as!cuscellTableViewCell

cell.txt_lbl.text = self.section[indexPath.row];
cell.sel_btn.tag = indexPath.row

let tuple = (section: indexPath.section, row: indexPath.row)
self.items[cell.sel_btn.hashValue] = tuple
cell.sel_btn.addTarget(self, action: #selector(self.switchChanged), forControlEvents: .ValueChanged)

return cell

}

func switchChanged(sender: AnyObject)
{
let switchControl: UISwitch = sender as! UISwitch
print("The switch is \(switchControl.on ? "ON" : "OFF")")

let tuple = self.items[switchControl.hashValue]
print(tuple.0) // this is the section
print(tuple.1) // this is the row

if switchControl.on
{
print("The switch is on lets martch")
}
}

关于ios - 如何从 TableView 中自定义单元格中的标签获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39031468/

27 4 0