Ibr*_*rar 2 uitableview ios swift
我花了几天时间来解决这个问题,经过多次努力,我在这里问一个问题.我正在使用自定义UITableViewCell,该单元格包含UITextFields.在向表视图添加新单元格时,表格视图表现异常,就像复制单元格一样,当我尝试编辑新单元格的文本字段时,前一个单元格的文本字段也会被编辑.
重复的行为如下:第一个单元格被复制为第三个单元格.我不知道这是由于细胞的可重用性,但有人能告诉我有效的解决方案吗?
我附上了UITableViewCell的截图.
cellForRow的代码如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : Product_PriceTableViewCell = tableView.dequeueReusableCell(withIdentifier: "product_priceCell") as! Product_PriceTableViewCell
cell.dropDownViewProducts.index = indexPath.row
cell.txtDescription.index = indexPath.row
cell.tfPrice.index = indexPath.row
cell.dropDownQty.index = indexPath.row
cell.tfTotalPrice_Euro.index = indexPath.row
cell.tfTotalPrice_IDR.index = indexPath.row
cell.dropDownViewTotalDiscount.index = indexPath.row
cell.dropDownViewDeposit.index = indexPath.row
cell.tfTotalDeposit_Euro.index = indexPath.row
cell.tfRemaingAfterDeposit_IDR.index = indexPath.row
return cell
}
Run Code Online (Sandbox Code Playgroud)
问题是UITableView正在重用单元格,这是您希望获得良好滚动性能的方法.
您应该更新支持表中每一行的数据源,以保存用户在字段中输入的文本.
然后从cellForRowAt中的数据源中分配文本字段的text属性.
换句话说,每次在屏幕上看到UITableViewCell都是相同的实例,UITextField也是如此,因此它的文本属性也是如此.这意味着每次调用cellForRowAt时都需要为其分配正确的文本值.
我不确定你的代码所以我提供了一个例子,说明我将如何做你想做的事情:
class MyCell: UITableViewCell {
@IBOutlet weak var inputField: UITextField!
}
class ViewController: UIViewController {
@IBOutlet weak var table: UITableView!
var items = [String]()
fileprivate func setupItems() {
items = ["Duck",
"Cow",
"Deer",
"Potato"
]
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupItems()
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// the # of rows will equal the # of items
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// we use the cell's indexPath.row to
// to get the item in the array's text
// and use it as the cell's input field text
guard let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? MyCell else {
return UITableViewCell()
}
// now even if the cell is the same instance
// it's field's text is assigned each time
cell.inputField.text = items[indexPath.row]
// Use the tag on UITextField
// to track the indexPath.row that
// it's current being presented for
cell.inputField.tag = indexPath.row
// become the field's delegate
cell.inputField.delegate = self
return cell
}
}
extension ViewController: UITextFieldDelegate {
// or whatever method(s) matches the app's
// input style for this view
func textFieldDidEndEditing(_ textField: UITextField) {
guard let text = textField.text else {
return // nothing to update
}
// use the field's tag
// to update the correct element
items[textField.tag] = text
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1653 次 |
| 最近记录: |