【问题标题】:accessing a text field in a tableView SWIFT访问 tableView SWIFT 中的文本字段
【发布时间】:2015-05-11 09:38:31
【问题描述】:

我有一个表格视图。当点击/选择单元格时,单元格会向下扩展以显示多个资产。一项资产是文本字段。另一个是“提交”按钮。

按下提交按钮时,我需要从文本字段访问用户输入。我该怎么做?

重要提示:我无法使用 didSelectRowAtIndexpath,因为单元格已被选中/展开。

目前我在 customCell 上有以下内容:

@IBAction func submitButtonPressed(sender: UIButton) {
    // prepareForSegue is on mainVC
    self.textString = self.textField.text
    println(self.textString) 
 }

在 MainVC 的“prepareForSegue”中,我有以下内容:

       var cell : CustomCell = self.tableView.dequeueReusableCellWithIdentifier("myCell") as! CustomCell

        let path = self.tableView.indexPathForSelectedRow()!
            println(cell.textField.text)
            self.newText = cell.textString
            self.newInt = self.newText.toInt()

            println(self.newText)
            println(self.newInt)

以下代码正确prints(self.textString) 然而, cell.textStringself.newTextself.newInt 始终是 nil

知道为什么吗?

【问题讨论】:

  • 给它一个唯一的标签,然后在视图中搜索带有该标签的元素
  • 标签是什么意思?不是 cell.textString 是标签吗?

标签: swift tableview segue custom-cell nsindexpath


【解决方案1】:

这是一个示例代码。

@IBAction func submitButtonPressed(sender: UIButton) {

        // prepareForSegue is on mainVC
            let indexPath = self.tableView!.indexPathForSelectedRow()!
            let selectedCell = self.tableView!.cellForRowAtIndexPath(selectedIndexPath!) as! UICustomCell!//your custom cell class.

            self.textString = selectedCell.textFied.text //textFied is your textfield name.
            println(self.textString) 
 }

对于 swift 2,此代码基于行索引工作

let indexPath = NSIndexPath(forRow: 1, inSection: 0) // This defines what indexPath is which is used later to define a cell
                let selectedCell = sptableViewObj.cellForRowAtIndexPath(indexPath) as! AddBillerTableViewCell!

                self.textFieldTwo = selectedCell.spTextfield.text //textFied is your textfield name.
                print(self.textFieldTwo)

【讨论】:

  • 太棒了,我将它添加到 segue(不是 CustomCell Viewcontroller 中的按钮,它似乎工作!是时候吃晚饭了,然后完全实现我的工作。谢谢 Amit89!
  • 这适用于所有 UITableViewCell 都可见的用户。当您有大约 10-15 个单元格并且您是第一个单元格不可见时,只需检查相同的内容。现在尝试访问第一个单元格。应用程序将崩溃。有人有同样的解决方案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多