Получить все значения из tableViewCell из TextFields - PullRequest
0 голосов
/ 04 февраля 2019

Я хочу получить все значения из TableViewCell с TextFields, но я не понимаю, как я могу это сделать, нажав на кнопку.

И я могу добавить новыйгрести, если я нажму на кнопку Add.Поэтому я могу сделать столько строк, сколько захочу.

Мой код здесь:

struct Section {
    let title: String
    var rows: [String]
}

class SettingsScheduleAndPricesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {

    var hall: Halls?

    var sections = [Section]()

    override func viewDidLoad() {
        super.viewDidLoad()
        sections = [Section(title: "Day of week", rows: []),
                    Section(title: "Second section", rows: [""]),
                    Section(title: "Third section", rows: [""])]
    }

    // MARK: - TableView
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].rows.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            ...
        } else if indexPath.section == 1 {
            let hourlyRateCell = tableView.dequeueReusableCell(withIdentifier: "hourlyRateCell", for: indexPath) as! SettingsHourlyRateCell
            return hourlyRateCell
        } else {
            ...
        }
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].title
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let frame: CGRect = tableView.frame
        if section == 0 {
            let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
            headerView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
            return headerView
        } else if section == 1 {
            let addButton: UIButton = UIButton(frame: CGRect(x: frame.size.width - 50, y: 0, width: 50, height: 30))
            addButton.backgroundColor = UIColor.clear
            addButton.setTitleColor(#colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1), for: .normal)
            addButton.setTitle(NSLocalizableAdd, for: .normal)
            addButton.addTarget(self, action: #selector(SettingsScheduleAndPricesViewController.addHourlyRate(sender:)), for: .touchUpInside)
            let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
            headerView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
            headerView.addSubview(addButton)
            return headerView
        } else {
            ...
        }
    }

    @IBAction func saveBarButtonPressed(_ sender: Any) {

        // here I want to get all values from my Cell from my TextFields

    }

    @objc func addHourlyRate(sender: UIButton) {
        let newRow = ""
        append(row: newRow, in: 1)
    }

    func append(row : String, in section: Int) {
        let insertionIndex = sections[section].rows.count
        sections[section].rows.append(row)
        let indexPath = IndexPath(row: insertionIndex, section: section)
        tableView.insertRows(at: [indexPath], with: .automatic)
    }
}

class SettingsHourlyRateCell: UITableViewCell, UITextFieldDelegate {
    @IBOutlet weak var rubHourTF: UITextField!
}

Мой пример с симулятора:

enter image description here

В моем примере мне нужно получить first, second и third текстовые строки из трех строк.И добавьте пустое array или просто напечатайте console.

В методе @IBAction func saveBarButtonPressed(_ sender: Any).

Я не смог найти ничего, что могло бы мне помочь.

Ответы [ 4 ]

0 голосов
/ 05 февраля 2019

Возможно, мой метод кому-нибудь поможет, но мне все-таки удалось сделать это таким образом.Я просто добавляю в мой button этот код:

@IBAction func saveBarButtonPressed(_ sender: Any) {
    let countRowsOne = tableView.numberOfRows(inSection: 1)
        for index in 0...countRowsOne {
            let indexPath = IndexPath(row: index, section: 1)
            if let cell = tableView.cellForRow(at: indexPath) as? SettingsHourlyRateCell {
                ...
            }
            ...
        }
    }
}
0 голосов
/ 04 февраля 2019

Текстовые поля в ячейках TableView могут быть хитрыми.Во-первых, используйте модель данных и reloadData () вместо insertRows (at :) следующим образом:

@objc func addHourlyRate(sender: UIButton) {
    let newRow: String = ""
    secondRowText.append(newRow)
    self.tableView.reloadData()
}

Теперь установите текст в ячейках и отметьте UITextField номером строки в cellForRowAt ()как это:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let hourlyRateCell = tableView.dequeueReusableCell(withIdentifier: "hourlyRateCell", for: indexPath) as! SettingsHourlyRateCell
   hourlyRateCell.rubHourTF.text = secondRowText[indexPath.row]
   hourlyRateCell.rubHourTF.tag = indexPath.row              
   return hourlyRateCell

}

Далее, используйте UITextFieldDelegate для отслеживания любых изменений в текстовых полях, что-то вроде:

func textFieldDidEndEditing(_ textField: UITextField) {
     let tableRow = textField.tag
     secondRowText[tableRow] = textField.text
} 

Обратите внимание, как тег textField был установлен в cellForRow () теперь используется, чтобы узнать, в какой строке находится textField в таблице.

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

Тег не требуется

@IBAction func saveBarButtonPressed(_ sender: Any) {
    var array = NSMutableArray()
    for subview in self.tableView.subViews {
         if subView.isKind(of: String(describing: SettingsHourlyRateCell.self)) {
            for sView in subview {
               if sView.isKind(of: String(describing: UITextField.self)) {   
                 array.add(sView.text)
            }
          }
       }
    }
}
0 голосов
/ 04 февраля 2019

вы можете создать протокол делегата для вашей ячейки

protocol cellDelegate {
func buttonClicked(textFieldText: String)}

и сделать переменную вашего протокола в вашей ячейке

var delegate: cellDelegate?

, а затем при событии нажатия кнопки вызвать метод изпеременная

delegate?.buttonClicked(textFieldText: "string you got from textField")

и в вашем табличном представлении cellForRowAt indexPath метод устанавливает делегат ячейки следующим образом: cell.delegate = self

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