文本在表格视图单元格之间移动

时间:2020-02-22 17:11:16

标签: ios swift uitableview tableview

我有一个包含多个部分的表格视图,每个部分中的行数不同。

我创建了一个自定义表格视图单元格。该单元格具有标签和文本字段。

此相同的自定义单元格用于表视图中的每个单元格。

当我在文本字段中输入一个值时,它会出现在其他一些文本字段以及其他行中。有时文本从我输入的文本字段中消失,并出现在下面的行中。当我上下滚动tableview时会发生这种情况。

这是我用于cellForRowAt的代码

let cell = tableView.dequeueReusableCell(withIdentifier:   "LabelTextFieldTableViewCell", for: indexPath) as! LabelTextFieldTableViewCell
    for i in approachSection {
        if Int(i.row) == indexPath.row {
            cell.myLabel.text = i.name
            cell.myTextField.placeholder = cell.setPlaceholder(type: i.type!)
            if i.type != CustomFieldType.text.rawValue {
                cell.isInteger = true
            }
        }
    }
return cell

自定义单元格是

class LabelTextFieldTableViewCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var myTextField: UITextField!

    var isInteger: Bool?
    var type: String!

    override func awakeFromNib() {
        super.awakeFromNib()
        myTextField.delegate = self
        myTextField.textAlignment = .right
        myTextField.borderStyle = .none


    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func setPlaceholder(type: String) -> String {
        switch type {
        case CustomFieldType.count.rawValue:
            return "#"
        case CustomFieldType.time.rawValue:
            return "Time as 1234"
        case CustomFieldType.text.rawValue:
            return "Enter Text"
        default:
            return ""
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.textColor = .black
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        guard textField.text != "" else { return }

        if isInteger != nil {
            guard checkIfIntegers(str: textField.text!) != false else {
                print("Not all Integers")
                textField.textColor = .red
                return
            }
        }
    }

}

2 个答案:

答案 0 :(得分:0)

在您的单元格子类中使用prepareToReuse方法。在这里,您应该将所有值重置为默认值,并在相应的cellForRowAtIndexPath方法中将适当的值设置为cell。

func prepareForReuse()

Apple documentation

在您的LabelTextFieldTableViewCell类中编写此方法 希望对您有帮助 快乐的编码=)

答案 1 :(得分:-1)

请确保您正确遵循此算法

  1. 首先,您将决定需要多少部分?
  2. 然后,您将决定一个节中需要多少行
  3. 然后,您将为单元中的每一行分配数据源模型,因为您不必使用for循环。 Index.row将为您完成这项工作。

注意:您可以在这些方法中使用switch语句来确定在特定部分显示多少行。

- tableView:cellForRowAtIndexPath: // required method

– tableView:numberOfRowsInSection: // required method

– numberOfSectionsInTableView:

– sectionIndexTitlesForTableView:

– tableView:sectionForSectionIndexTitle:atIndex:

– tableView:titleForHeaderInSection:

– tableView:titleForFooterInSection:
相关问题