从表格视图单元格中删除UIlabel文本

时间:2017-03-08 08:38:55

标签: ios swift uitextfield

我有一个表视图并使用自定义单元格。现在我在我的酒吧设置了一个清晰的按钮。现在单击该UIBarButton我想清除单元格中文本字段内的所有文本。我怎么能这样做.. ??

  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")


}

2 个答案:

答案 0 :(得分: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

                }
            }
        }
    }

答案 1 :(得分: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
      }
   }
}
相关问题