【发布时间】:2016-07-03 13:20:17
【问题描述】:
我有两个 ViewController。一个有一个 TableView 和一个 Add Button,它将我们带到第二个 ViewController,它有一个文本字段和一个操作按钮。用户应该将文本插入到具有文本字段的第二个屏幕上的表格视图中。
我为两个视图控制器制作了单独的 swift 文件。对于第二个视图,我正在导入我的第一个视图的类。但是,当我尝试点击添加按钮转到第二个视图控制器时,我收到一个可选的包装错误。这是我得到的错误:致命错误: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 我的 TableView 已经连接到 DataSource 和 Delegate。我在情节提要中做到了。你这是什么意思?你能解释一下吗?我还设置了单元格和所有内容,但此处未显示代码
-
您的
tableview出口似乎是nil。你把它连接到故事板了吗? -
@vacawama 是的。它连接到数据源和委托。实际上,我注意到的一件有趣的事情是,对于我的第二个视图控制器文件,如果我说“class TextScreen : UIViewController”,我成功地转换到了第二个控制器。但是,如果父类是 MainScreen (第一个视图控制器),我会收到此错误。为什么会这样?
-
这个属性
@IBOutlet weak var tableview: UITableView!也必须连接到tableView。仅仅连接代理和数据源是不够的。
标签: ios swift uitableview uiviewcontroller uitextfield