2017-03-08 101 views
1

我有一個表格視圖併爲此使用自定義單元格。現在我在我的酒吧裏設置了一個清晰的按鈕。現在單擊該UIBarButton,我想清除單元格中文本字段內的所有文本。我怎樣才能做到這一點..??刪除表格視圖單元格中的UIlabel文本

var DataSource = [NewAssessmentModel]() 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.DataSource.count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let model = self.DataSource[indexPath.row] 


    switch(model.assessmentControlType) 
    { 
    case .text: 
     let cell = (tableView.dequeueReusableCellWithIdentifier("QuestionWithTextField", forIndexPath: indexPath) as? QuestionWithTextField)! 
     cell.model = model 
     cell.indexPath = indexPath 
     cell.txtAnswer.delegate = self 
     cell.lblQuestion.text = model.labelText 
     cell.indexPath = indexPath 

     return cell 
    } 
    } 

現在單元格包含一個txtAnswer作爲UITextField。我如何清除txtAnswer的文本字段。

清除字段:

func clearView(sender:UIButton) 
{ 
    print("Clear Button clicked") 


} 
+0

按下「清除」按鈕後,你想要在'dataSource'中的數據發生什麼?你想保留數據,只是清除標籤? – Eendje

+0

清除UIText字段 – Sam

+0

問題是要求'txtAnswer',而不是'lblQuestion'。爲什麼下面的答案是指'lblQuestion'? – chengsam

回答

1

你可以得到的tableView的所有可見單元格。

@IBAction func deleteText(_ sender: Any) { 
    for cell in tableView.visibleCells { 
     if let questionCell = cell as? QuestionWithTextField { 
     // Hide your label here. 
     // questionCell.lblQuestion.hidden = true 
     } 
    } 
} 
+0

刪除txtAnswer UITextField .. ?? – Sam

+0

如果你想隱藏,只是使用隱藏的屬性'questionCell.lblQuestion.hidden = true' –

+0

謝謝它的工作 – Sam

2

上述代碼僅適用於可見的單元格。如果在手機中不可見,單元格值將不會被清除。

爲此,您需要遍歷每個表視圖單元格。我認爲這是你最好的選擇之一。

func clearView(sender:UIButton) 
    { 
     print("Clear Button clicked") 
     for view: UIView in tableView.subviews { 
      for subview: Any in view.subviews { 
       if (subview is UITableViewCell) { 
        let cell = subview as? UITableViewCell 
        // do something with your cell 

        if let questioncell = cell as? QuestionWithTextField 
        { 
         questioncell.txtField.text = "" 
        } 

        // you can access any cells 

       } 
      } 
     } 
    } 
相關問題