Чтение данных из 2-х текстовых полей для каждого TableViewCell - PullRequest
0 голосов
/ 04 января 2019

Как сказано в названии;Я хочу прочитать данные из нескольких UITextField с для каждой ячейки и сохранить их в массиве.Как бы я это сделал?

Я создал подкласс CustomCell, в котором 2 UITextFields.P / S: идентификатор для ячейки также CustomCell

Большое спасибо

class TableViewController : UITableViewController, UITextFieldDelegate {
var data = [input]()

@IBOutlet var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let customCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell

    customCell.input1.tag = indexPath.row
    customCell.input2.tag = indexPath.row
    customCell.input1.delegate = self
    customCell.input2.delegate = self

    return customCell
}

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

@IBAction func addButton(_ sender: Any) {
    table.beginUpdates()
    table.insertRows(at: [IndexPath(row: data.count-1, section: 0)], with: .automatic)
    table.endUpdates()
}

func textFieldDidEndEditing(_ textField: UITextField) {
    let indexPath = IndexPath(row: textField.tag, section: 0)

    if let customCell = self.table.cellForRow(at: indexPath) as? CustomCell{

        let a = customCell.Credit.text!.isEmpty ? no:String(customCell.input1.text!)
        let b = customCell.letterGrade.text!.isEmpty ? no:String(customCell.input2.text!))

        inputRead.append(input(string1: a, string2: b))

    }

 @IBAction func foo(_ sender: Any) {
    if inputRead.count == 0{
        return
    }
    //the rest of implementation

}

Класс CustomCell:

Import UIKit

public class CustomCell: UITableViewCell {

    @IBOutlet weak var input1: UITextField!
    @IBOutlet weak var input2: UITextField!

}

Ответы [ 2 ]

0 голосов
/ 04 января 2019

Это может помочь вам сохранить текст в массиве: -

1: добавить indexPath.row в качестве тега к вашему textField в cellForRowAt

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  

    let customCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

    customCell.input1.tag = indexPath.row
    customCell.input2.tag = indexPath.row
    customCell.input1.delegate = self
    customCell.input2.delegate = self

    return customCell
}

2: В методе делегата textField вы можете получить текст textField

func textFieldDidEndEditing(_ textField: UITextField) {

    let indexPath = IndexPath(row: textField.tag, section: 0)

    if let customCell = self.table.cellForRow(at: indexPath) as? CustomCell {

        //From here you can get your particular input1 or input2 textfield text
         print(customCell.input1.text)
         print(customCell.input2.text)
    }
}
0 голосов
/ 04 января 2019

Обновите ваш код следующим образом в вашем контроллере представления.

Назначьте делегирование себя текстового поля ViewController в cellForRowAt

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  
    let customCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

    customCell.input1.delegate = self
    customCell.input2.delegate = self

    return customCell
}

Теперь реализован делегат текстового поля в вашем контроллере представления.

func textFieldDidEndEditing(_ textField: UITextField) {
    guard let jobTaskCell = textField.superview?.superview as? CustomCell else {
        return
    }

    if textField == jobTaskCell.input1 {
        // Get text from textfield and store in array
    } else if textField == jobTaskCell.input2 {
        // Get text from textfield and store in array
    }
}

Примечание: Следующий код зависит от того, как разместить текстовое поле в вашей ячейке.Поэтому убедитесь, что вам нужно проверить это рекурсивно, добавив и удалив superView

guard let jobTaskCell = textField.superview?.superview as? CustomCell else {
    return
}

Это просто означает, что только для текстового поля внутри ячейки табличного представления без какого-либо дополнительного представления:

textField.superview = contentView TableViewCell

textField.superview? .Superview = TableViewCell

Надеюсь, это исправит вашвыпуск.

...