Обнаружение текстовых полей должно возвращаться из Custom TableViewCell в TableViewController для добавления новой строки - PullRequest
1 голос
/ 13 апреля 2020

Я хочу добавить новую строку в мой TableView, когда пользователь нажимает клавишу возврата внутри Custom TableViewCell, который включает TextField. Однако я не могу найти способ сделать это ... как мне просмотреть события TextField в моем TableView, чтобы я мог добавить строку?

My TableViewController

class TableViewController: UITableViewController, CustomCellDelegate,
UITextFieldDelegate {

    var rowCount = 1

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

    // MARK: - Table view data source

    ...

    // Doesn't Do Anything
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let indexPath = IndexPath(row: rowCount-1, section: 1)
        tableView.insertRows(at: [indexPath], with: .automatic)
        view.endEditing(true)
        return true
    }

    // Also does nothing
    func didReturn(cell: AddActivityTableViewCell, string: String?) {
        let indexPath = IndexPath(row: rowCount-1, section: 1)
        tableView.insertRows(at: [indexPath], with: .automatic)
        view.endEditing(true)
        rowCount += 1
    }

My CustomTableViewCell

protocol CustomCellDelegate: class {
    func didReturn(cell: CustomTableViewCell, string: String?)
}

class CustomTableViewCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!
    weak var delegate: CustomCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        textField.delegate = self
    }

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

        // Configure the view for the selected state
    }

    public func configureTextField(text: String?, placeholder: String) {
        textField.text = text
        textField.placeholder = placeholder

        textField.accessibilityValue = text
        textField.accessibilityLabel = placeholder
    }

    public func editableTextField(editable: Bool) {
        if editable == true {
            textField.isEnabled = true
        } else {
            textField.isEnabled = false
        }
    }

    // This works
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        delegate?.didReturn(cell: self, string: textField.text)
        return true
    }
}

Спасибо!

1 Ответ

1 голос
/ 13 апреля 2020

Я думаю, что вы пропустили установленного делегата в ячейке. Пожалуйста, найдите код ниже, который отлично работает для меня

ViewController

class TableViewController: UITableViewController, CustomCellDelegate, UITextFieldDelegate {


var rowCount = 1

override func viewDidLoad() {
    super.viewDidLoad()

}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return rowCount
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
    cell.textField.placeholder = "Row \(indexPath.row)"
    cell.delegate = self
    return cell
}

func didReturn(cell: CustomTableViewCell, string: String?) {
    rowCount += 1
    let indexPath = IndexPath(row: rowCount-1, section:0)
    tableView.beginUpdates()
    tableView.insertRows(at: [indexPath], with: .automatic)
    tableView.endUpdates()
    view.endEditing(true)
}


}

Custom Cell

protocol CustomCellDelegate: class {
    func didReturn(cell: CustomTableViewCell, string: String?)
}

class CustomTableViewCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!
    weak var delegate: CustomCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        textField.delegate = self
    }

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

        // Configure the view for the selected state
    }

    public func configureTextField(text: String?, placeholder: String) {
        textField.text = text
        textField.placeholder = placeholder

        textField.accessibilityValue = text
        textField.accessibilityLabel = placeholder
    }

    public func editableTextField(editable: Bool) {
        if editable == true {
            textField.isEnabled = true
        } else {
            textField.isEnabled = false
        }
    }

    // This works
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        delegate?.didReturn(cell: self, string: textField.text)
        return true
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...