У меня есть два ViewControllers. У одного есть TableView и кнопка Add, которая ведет нас ко второму ViewController, у которого есть текстовое поле и кнопка действия. Предполагается, что пользователь должен вставить текст в таблицу на втором экране с текстовым полем.Ошибка при переключении с одного контроллера вида на другой
Я сделал отдельные быстрые файлы для двух контроллеров представления. Для второго представления я импортирую класс своего первого представления. Однако, когда я пытаюсь нажать кнопку добавления, чтобы перейти ко второму контроллеру представления, я получаю дополнительную ошибку обертывания. Это ошибка, которую я получаю: фатальная ошибка: unexpectedly found nil while unwrapping an Optional value. И в режиме отладки, он выделяет следующую строку кода:
tableview.setEditing(true, animated: true)
код для моего первого контроллера представления, который имеет TableView:
class MainScreen : UIViewController, UITableViewDataSource, UITableViewDelegate {
var items = ["Apple", "Fish", "Dates", "Cereal", "Ice cream", "Lamb", "Potatoes", "Chicken", "Bread"]
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableview.setEditing(true, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let iD = "normal"
let cell = tableView.dequeueReusableCellWithIdentifier(iD, forIndexPath: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
if (sourceIndexPath.row != destinationIndexPath.row){
let temp = items[sourceIndexPath.row]
items.removeAtIndex(sourceIndexPath.row)
items.insert(temp, atIndex: destinationIndexPath.row)
}
tableView.reloadData()
}
}
Код для моего второго контроллера представления который имеет текстовое поле и кнопку для ввода текста в мой массив (позиции)
class TextScreen : MainScreen {
@IBOutlet weak var keyboard: UITextField!
@IBAction func insert(sender: AnyObject) {
items.append(keyboard.text!)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Я не знаю, что я делаю неправильно. Я также добавил скриншот.
Вам необходимо реализовать требуемые функции UITableViewDataSource и UITableViewDelegate – Roee84
@ Roee84 My TableView уже подключен к DataSource и Delegate. Я сделал это в Раскадровке. Что ты хочешь этим сказать? Не могли бы вы объяснить больше? Я также установил ячейки и все, но код здесь не показан. –
Похоже, что ваша версия 'tableview' -' nil'. Вы связали его с раскадрой? – vacawama