Добавить ячейку в UITableView, если текстовое поле предыдущей ячейки заполнено - PullRequest
0 голосов
/ 07 сентября 2018

У меня есть UITableView в моем ViewController. Каждая ячейка содержит textfield, где кто-то может ввести новый текст (список дел). Теперь я хочу добавить новую ячейку, которая уже содержит новый textfield, только если textfield предыдущей ячейки содержит текст.

В настоящее время я использую UIButton для добавления новой ячейки, и это работает и изменяет размеры табличного представления, чтобы все ячейки были видны, но я хочу, чтобы это было автоматизировано после заполнения предыдущей ячейки, чтобы она стала более удобной для пользователя.

Так выглядит моя раскадровка.

И вот код, который я сейчас использую для добавления новой строки:

    @IBAction func btnAddRow_TouchUpInside(_ sender: Any) {

    toDoTableView.beginUpdates()
    amountCells.append("")
    self.toDoTableView.insertRows(at: [IndexPath.init(row: self.amountCells.count - 1, section: 0)] , with: .automatic)
    toDoTableView.endUpdates()
    tblHeight.constant = toDoTableView.contentSize.height

}

Есть идеи, как мне это сделать? Заранее спасибо.

РЕДАКТИРОВАТЬ: я пытался использовать EditingDidEnd

    class TextFieldsCell: UITableViewCell {

    @IBOutlet weak var txtToDo: UITextField!

    @IBAction func txtToDo_EditingDidEnd(_ sender: Any) {
            if(!(txtToDo.text?.isEmpty)! {
                print("Insert Code to Add New Row")
            }
        }
}

Когда я это делаю, я не могу получить доступ к toDoTableView с моего ViewController. Другая проблема, к которой это может привести, заключается в том, что когда уже есть 5 строк, а первая просто редактируется, вставляется другая строка, а я этого не хочу.

Ответы [ 4 ]

0 голосов
/ 07 сентября 2018

В конце концов исправили, объединив ответы @Mauli и @Vicky_Vignesh / @ Kuldeep.

    func textFieldDidEndEditing(_ textField: UITextField) {
    let rowBeingEditedInt = textField.tag
    let indexPath = IndexPath(row:rowBeingEditedInt , section:0 )
    let cell = toDoTableView.cellForRow(at: indexPath) as! TextFieldsCell
    let table: UITableView = cell.superview as! UITableView

    let textFieldIndexPath = table.indexPath(for: cell)
    if textFieldIndexPath?.row == (amountCells.count - 1) {

        if(!(cell.txtToDo.text?.isEmpty)!) {
            toDoTableView.beginUpdates()
            amountCells.append("")
            self.toDoTableView.insertRows(at: [IndexPath.init(row: self.amountCells.count - 1, section: 0)] , with: .automatic)
            toDoTableView.endUpdates()
            tblHeight.constant = toDoTableView.contentSize.height
        }

    }

}

Спасибо, ребята! Очень ценится.

0 голосов
/ 07 сентября 2018

Вы можете проверить, является ли текстовое поле пустым или нет в самом viewController. Вы просто подтверждаете делегат для текстового поля из раскадровки и в cellForRowAt и присваиваете тег этому текстовому полю

например,

cell.yourTextField.delegate = self
cell.yourTextField.tag = indexPath.row

и убедитесь, что текстовое поле пусто или нет в textField делегат метод. Создайте объект ячейки в методе, подобном

func textFieldDidEndEditing(_ textField: UITextField) {
     rowBeingEditedInt = textField.tag
     let indexPath = IndexPath(row:rowBeingEdited! , section:0 )
     let cell = yourTableView.cellForRow(at: indexPath) as! yourTableViewCell
  // check cell.yourtextField.text isempty and do your condition
 }
0 голосов
/ 07 сентября 2018

Вы можете попробовать это.

В cellForRowAt метод установлен UITableViewCell textField делегат первым.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:TableViewCell = self.tblvw.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    cell.txtField.delegate = self
    cell.txtField.tag = indexPath.row
    cell.txtField?.text = amountCells[indexPath.row]

    return cell
}

В textFieldDidEndEditing вам просто нужно проверить ниже, исходя из того, что вы выполняете свое дальнейшее задание.

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    return textField.resignFirstResponder()
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField.text?.count == 0 || textField.tag != self.amountCells.count - 1 {

    }
    else {
        self.tblvw.beginUpdates()
        amountCells.append("")
        self.tblvw.insertRows(at: [IndexPath.init(row: self.amountCells.count - 1, section: 0)] , with: .automatic)
        self.tblvw.endUpdates()
    }
}
0 голосов
/ 07 сентября 2018

Добавьте это к вам textfield делегируйте и замените tableview именем вашей таблицы

func textFieldDidEndEditing(textField: UITextField!){

    var cell: UITableViewCell = textField.superview.superview as UITableViewCell
    var table: UITableView = cell.superview as UITableView
    let textFieldIndexPath = table.indexPathForCell(cell)
    if textFieldIndexPath.row == (yourdataArray.count - 1)
    {
        print("came to last row")

        if ((textField.text?.count)! > 0){

            print("text available")

            toDoTableView.beginUpdates()
            amountCells.append("")
            self.toDoTableView.insertRows(at: [IndexPath.init(row:
                self.amountCells.count - 1, section: 0)] , with: .automatic)
            toDoTableView.endUpdates()
            tblHeight.constant = toDoTableView.contentSize.height
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...