Как сделать UITableview с текстовым полем быстрым?
Я хочу сделать представление таблицы с текстовыми полями в каждой ячейке,
У меня есть собственный класс в быстром файле:
import UIKit
public class TextInputTableViewCell: UITableViewCell{
@IBOutlet weak var textField: UITextField!
public func configure(#text: String?, placeholder: String) {
textField.text = text
textField.placeholder = placeholder
textField.accessibilityValue = text
textField.accessibilityLabel = placeholder
}
}
Затем в моем ViewController у меня есть
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("TextInputCell") as! TextInputTableViewCell
cell.configure(text: "", placeholder: "Enter some text!")
text = cell.textField.text
return cell
}
Это хорошо работает:
![введите описание изображения здесь]()
Но когда пользователь вводит текст в текстовое поле и нажимает кнопку, я хочу сохранить строки каждого текстового поля в массиве.
Я пробовал с
text = cell.textField.text
println(text)
Но он ничего не печатает, если он пуст
Как я могу заставить его работать?
Ответы
Ответ 1
В вашем представлении контроллер становится UITextFieldDelegate
Контроллер просмотра
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
var allCellsText = [String]()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell
cell.theField.delegate = self // theField is your IBOutlet UITextfield in your custom cell
cell.theField.text = "Test"
return cell
}
func textFieldDidEndEditing(textField: UITextField) {
allCellsText.append(textField.text)
println(allCellsText)
}
}
Это всегда добавляет данные из текстового поля в массив allCellsText.
Ответ 2
создать переменную
var arrayTextField = [UITextField]()
после этого в func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{}
добавить
self.arrayTextField.append(textfield)
перед возвратом ячейки, после этого для отображения значений с помощью
for textvalue in arrayTextField{
println(textvalue.text)
}
Ответ 3
этот метод инициализирует ячейку, и у вас нет модели для сохранения этих данных, поэтому
text = cell.textfield.text
ничего!
вы можете инициализировать var textString
в viewcontroller, наследовать UITextFieldDelegate
optional func textFieldDidEndEditing(_ textField: UITextField)
{
textString = _textField.text
}
optional func textFieldShouldReturn(_ textField: UITextField) -> Bool{
return true
}
и cell.textField.text = textString