2015-05-11 44 views
1

我有一个tableView。当单元格被轻敲/选中时,单元格向下展开以显示多个资产。一个资产是一个文本字段。另一个是“提交”按钮。访问tableView中的文本字段SWIFT

当按下“提交”按钮时,我需要从文本字段访问用户输入。我怎样才能做到这一点?

重要说明:我无法使用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

任何想法为什么?

+1

给它一个独特的标记,然后用该标签 – Jasper

+0

你是什么意思,标签搜索视图的元素?不是cell.textString它的标签? –

回答

5

这里是一个示例代码。

@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) 
+0

真棒,我添加到segue(而不是在CustomCell Viewcontroller中的按钮,它似乎工作!时间去吃晚饭,然后全面实施我的工作。谢谢你Amit89! –

+1

这适用于那些在所有的UITableViewCell都是可见的,当你有10-15个单元并且你是第一个单元格不可见时,请检查它,现在尝试访问第一个单元格,应用程序将崩溃。 –