从 TableView iOS 中的 TableViewCells 获取参考 [英] Get Reference From TableViewCells in TableView iOS

查看:25
本文介绍了从 TableView iOS 中的 TableViewCells 获取参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次做一个具有通用"设计的应用程序,其中 textFields 和按钮在 tableView 单元格内.我很难在我的动态 tableView 单元格中获取 texFields 的值.

It is my first time to do an app that has a 'generic'-ish design, in which the textFields and buttons are inside the tableView cells. I'm having quite a hard time getting the values of the texFields in my dynamic tableView cells.

这是我的代码:

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() 函数时,它会使应用程序崩溃.任何想法如何正确获取这些动态单元格中的 textFields 的值?

It works, however, it crashes the app when you scroll to the bottom of the tableView and you attempt to call this submit() function. Any ideas how to properly get the values of the textFields inside these dynamic cells?

崩溃指向 nameCell

致命错误:解包可选值时意外发现 nil

推荐答案

尝试做一个if let"以获得这个可选值并避免 nil 值崩溃

Try to do an "if let" in order to get this optional value and avoid the crash with nil values

示例:

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

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

And for getting the values of the TextFields inside the cell I like to assign a Tag to each TextField and then get the value by this way:

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!"
}

这篇关于从 TableView iOS 中的 TableViewCells 获取参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆