2015-05-11 88 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個單元並且你是第一個單元格不可見時,請檢查它,現在嘗試訪問第一個單元格,應用程序將崩潰。 –