此代码来自现在非活动的教程,它帮助我将数据加载到表格视图。由于本教程是用Swift 2.0编写的,我相信这在Swift 3中有所改变。我知道override函数本身发生了变化,我处理了这个函数。但现在,它给我带来了一个Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)
错误。Swift 3在索引路径中为行打破单元格
更新:我尝试过多种方法,包括为单元格创建自定义类。我仍然得到了上面列出的同样的错误,或者在我的App Delegate文件的第一行中出现了Thread 1: Signal SIGABRT
错误。创建一个断点并没有帮助我,因为我知道错误来自哪里。
import UIKit
import Firebase
import FirebaseDatabase
struct postStruct {
let title : String!
let message : String!
}
class LoggedInController: UITableViewController {
var posts = [postStruct]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("Posts").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let snapshotValue = snapshot.value as? NSDictionary
let title = snapshotValue!["title"] as? String
let message = snapshotValue!["message"] as? String
self.posts.insert(postStruct(title: title, message: message), at: 0)
self.tableView.reloadData()
})
post()
}
func post(){
let title = "Title"
let message = "Message"
let post : [String : AnyObject] = ["title" : title as AnyObject,
"message": message as AnyObject]
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("Posts").childByAutoId().setValue(post)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell")
let label1 = cell?.viewWithTag(1) as! UILabel
label1.text = posts[indexPath.row].message
let label2 = cell?.viewWithTag(2) as! UILabel
label2.text = posts[indexPath.row].message
return cell!
}
}
更新2:这里是我用的新代码。这不太好,只能得到冠军。
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell?.textLabel?.text = posts[indexPath.row].title
cell?.detailTextLabel?.text = posts[indexPath.row].message
return cell!
} else {
let label1 = cell?.viewWithTag(1) as? UILabel
label1?.text = posts[indexPath.row].title
let label2 = cell?.viewWithTag(2) as? UILabel
label2?.text = posts[indexPath.row].message
return cell!
}
}
请看[这里](https://developer.apple.com/reference/uikit/uitableview/1614983-cellforrow)我相信唯一改变的就是func的方法签名,所以只需要输入'cellFor '和自动完成会弹出可能的东西 – Honey
最有效的解决方案是在Interface Builder中使用IBOutlets创建**自定义**单元。至少从Xcode 6开始,'viewWithTag'方式已经过时了。 – vadian
@vadian我已经将单元格类型设置为自定义。我不确定如何用IBOutlets来做到这一点。 –