我有一个带有动态单元格的UITableView
(在以前的视图中,是用于创建这些单元格的滑块)。
每行包含两个TextField。
首先是离起点的距离。
其次是描述。
我可以通过tableView中的单元格访问这些textField。
我的tableView:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell: FirstAddPointTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! FirstAddPointTableViewCell
cell.numberOfCell.text? = "\(indexPath.row + 1)."
cell.distance.text? = arrayTextField1[indexPath.row]
cell.description.text? = arrayTextField2[indexPath.row]
cell.distance.tag = indexPath.row
cell.description.tag = indexPath.row
cell.distance.delegate = self
cell.description.delegate = self
return cell
我的代码中有func
textFieldDidEndEditing
,但是我不知道如何访问textFields-距离和说明,以便将正确的值保存到两个数组中。我知道此代码仅适用于一个textField。如果我有两个textFields,则此代码是错误的:
func textFieldDidEndEditing(_ textField: UITextField) {
print("End editing!")
if textField.text != "" {
arrayTextField1[textField.tag] = textField.text!
arrayTextField2[textField.tag] = textField.text!
} else if textField.text == "" {
arrayTextField1[textField.tag] = textField.text!
arrayTextField2[textField.tag] = textField.text!
}
}
有我的FirstAddPointTableViewCell:
import UIKit
class FirstAddPointTableViewCell: UITableViewCell {
@IBOutlet weak var cislovaniPrekazek: UILabel!
@IBOutlet weak var prekazkyFormulare: UITextField!
@IBOutlet weak var poznamkyFormulare: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
我的“想法”类似于此代码(在
textFieldDidEndEditing
中),但我不知道该怎么做。我无法访问它们: arrayTextField1[distance.tag] = distance.text!
arrayTextField2[description.tag] = description.text!
你能帮我吗?对不起我的英语不好。
最佳答案
在一次调用textFieldDidEndEditing()的过程中尝试同时设置arrayTextField1和arrayTextField2似乎不正确。您需要将已编辑的textField关联到正确的数组。
一种想法是在每个UITextField的标签中编码额外的信息。您所需的一切如下所示,我们利用标记是带符号整数的事实:
// In your tableView cellForRowAt method edit the tag setting lines as such:
cell.distance.tag = indexPath.row + 1 // tag will be 1-based since -0 == 0
cell.description.tag = -(indexPath.row + 1) // store it as a negative row so we can distinguish description text fields later
func textFieldDidEndEditing(_ textField: UITextField)
{
guard let text = textField.text else { return }
if textField.tag > 0
{
arrayTextField1[textField.tag - 1] = text
}
else if textField.tag < 0
{
arrayTextField2[abs(textField.tag - 1)] = text
}
else
{
assert(true) // some other text field ended editing?
}
}
如果采用上述方法,请确保将标签计算封装在某些函数中,以确保将来的可维护性。
将任何数量的数据附加到UIView而不进行子类化的更优雅的解决方案是here。