我有用於添加配方指令(步驟)的TableView。第一個單元格給出,用戶可以根據需要添加更多單元格。 用戶可以刪除他們不需要的單元格。Swift 2.1 - 刪除單元格後在TableViewCell中清除文本字段
每個單元格(行)都配置有指令文本內容的UITextfield和用於標記指令順序的UILabel。
其中一種可能的用例可能是該用戶在單元格中鍵入了一些文本,並決定將其刪除以重新開始。當用戶按添加步驟按鈕時,用戶將看到一個新的單元格,但前面的文本已填充。 爲了防止出現這種情況,我有cell.stepTextField.text = ""
,以便用戶可以獲得具有明確文本字段的單元格。
這是一種有效的工作,但是當我玩很多可能的互動時,我會得到有趣的結果,如附加的截圖。在該示例屏幕截圖中,即使我沒有刪除該單元格,我仍然在第一個單元格中丟失了指令。
如何確保用戶每次都會得到一個乾淨的文本字段,而不會丟失其他單元格的文本?
我也試過cell.stepTextField.removeFromSuperview()
也,但這將完全刪除一個單元格的文本字段,這不是我想要的。
請注意,我在刪除函數中沒有對DataSource進行任何更新,因爲我只能獲得保存函數中tableview的所有文本字段的值。
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if tableView == stepTableView {
if editingStyle == .Delete {
// Delete the row from the data source
if stepOrder.count > 1 {
let cell = self.stepTableView.cellForRowAtIndexPath(indexPath) as! StepCell?
cell!.stepTextField.text = ""
stepTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
(更新) 的cellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == self.stepTableView {
let aCell = tableView.dequeueReusableCellWithIdentifier("StepCell", forIndexPath: indexPath) as! StepCell
stepTextField = aCell.getTextField()
aCell.configureStepOrder(stepOrder[indexPath.row])
aCell.stepTextField.delegate = self
cell = aCell
}
}
將標記添加到cellforRowAtIndex方法中的textfield中,然後您可以在刪除單元格的同時清除特定的textfiled文本值 – swiftBoy
您可以共享cellForRowAtIndexPath方法的代碼嗎? –
@SeongLee你會得到奇怪的結果,因爲你正在重複使用單元格,並且不保存用戶所做的更改... –