2017-05-07 117 views
0

我有自定義UITableViewCell其中包含文本字段。問題出現在我在第一個文本字段中輸入一些文本後(例如)在滾動tableView後,此文本在另一個單元格中複製。我知道,這是因爲tableView出隊單元。
處理這個問題的正確方法是什麼?
我的代碼:
滾動tableview時複製數據查看

@IBOutlet weak var tableView: UITableView! 

     var dataArray: [String] = [] 

     override func viewDidLoad() { 
     super.viewDidLoad() 

     tableView.dataSource = self 

     for i in 0...50 { 
      dataArray.append("Elemnt # \(i)") 
     } 
     } 
    } 

    extension ViewController: UITableViewDataSource { 
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return dataArray.count 
     } 

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell") 
     return cell 

    } 

回答

1

你出列的單元格中的-tableView:cellForRowAtIndexPath:方法後立刻就可以訪問它關聯的文本字段,並清除它。

或者,如果您有子類UITableViewCell,則可以覆蓋子類中的prepareForReuse()方法並執行相同的操作。

+0

謝謝。我會嘗試你的解決方案 – makedonskii

1

1。需要創建一個單獨的陣列與初始textValue:

var stringArray:[String] = ["", "", "", ""] 
  • 分配值中的cellForRowAtIndexPath

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") 
    
    cell.textfield.text = stringArray[indexpath.row] // change your swift syntax 
    
  • 3至文本框。在textFieldDidEndEditing中替換該初始值。

    func textFieldDidEndEditing(_ textField: UITextField) { 
          let buttonPosition:CGPoint = textField.convert(CGPointZero, 
          to:self.tableView) 
          let indexPath = self.tableView.indexPathForRow(at: buttonPosition) 
          stringArray[indexPath.row] = textField.text 
          println(allCellsText) 
          self.tableView.reloadData() // or you can reload specific cell 
         } 
        } 
    
    +0

    這個工作嗎? – KKRocks