【问题标题】:Get Reference From TableViewCells in TableView iOS从 TableView iOS 中的 TableViewCells 获取参考
【发布时间】:2016-12-28 14:13:56
【问题描述】:

这是我第一次做一个具有“通用”设计的应用程序,其中文本字段和按钮在 tableView 单元格内。我很难在我的动态 tableView 单元格中获取 texFields 的值。

这是我的代码:

func submit() {

    // cells
    let nameCell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 1)) as! ProductDetailTableViewCell
    let shortDescriptionCell = self.tableView.cellForRow(at: IndexPath(row: 1, section: 1)) as! ProductDetailTableViewCell

    // data
    let name = nameCell.textField_Detail.text!
    ...
    ...
}

它可以工作,但是,当您滚动到 tableView 的底部并尝试调用此 submit() 函数时,它会使应用程序崩溃。任何想法如何正确获取这些动态单元格内的文本字段的值?

编辑: 崩溃点指向 nameCell

致命错误:在展开可选值时意外发现 nil

【问题讨论】:

  • 崩溃时的信息是什么?
  • 另外,它在哪一行崩溃?
  • 看编辑,伙计们。
  • cellForRow 可能返回的不是ProductDetailTableViewCell,这是它返回的唯一类型吗?
  • @Samantha,是的,ProductDetailTableViewCell 适用于整个 section1 和 section3。 section0 和 section2 不同。

标签: ios swift uitableview


【解决方案1】:

尝试执行“if let”以获取此可选值并避免 nil 值崩溃

例子:

if let myNameCell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 1)) as! ProductDetailTableViewCell{
    // Here you must use 'myNameCell'
}

为了获取单元格内 TextFields 的值,我喜欢为每个 TextField 分配一个标签,然后通过这种方式获取值:

if let myNameCell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 1)) as! ProductDetailTableViewCell{
   (myNameCell.contentView.viewWithTag(3) as! UILabel).text = "bla bla bla"
   (myNameCell.contentView.viewWithTag(3) as! UITextField).text = "Some text!"
}

【讨论】:

  • TAGS 是唯一的办法呵呵。谢谢!
猜你喜欢
  • 2015-02-24
  • 1970-01-01
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 2023-03-05
  • 1970-01-01
相关资源
最近更新 更多