我想將事件對象傳遞到DetailViewController,但它崩潰並說:「致命錯誤:意外地發現零,同時解開一個可選值」。我是積極的錯誤是在我的準備(賽格:)功能,但我已經在這個小時,我找不出如何解決它。任何幫助,將不勝感激。謝謝!Swift prepareForSegue對象是無
這裏是我的代碼:
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var tableView: UITableView!
var events = [Event]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
parseCSV()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func logOutAction(sender: AnyObject) {
if FIRAuth.auth()?.currentUser != nil {
do {
try FIRAuth.auth()?.signOut()
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUp")
present(vc, animated: true, completion: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
func parseCSV() {
let path = Bundle.main.path(forResource: "eventData", ofType: "csv")
do {
let csv = try CSV(contentsOfURL: path!)
let rows = csv.rows
for row in rows {
let eventTitle = row["Title "]!
let eventLoc = row[" Location "]!
let eventStart = row[" Start_Time "]!
let eventEnd = row [" End_Time"]!
let event = Event(title: eventTitle, loc: eventLoc, start: eventStart, end: eventEnd)
events.append(event)
}
} catch let err as NSError {
print(err.debugDescription)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as? EventCell{
let event = events[indexPath.row]
cell.updateUI(event: event)
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let event = events[indexPath.row]
performSegue(withIdentifier: "detailSegue", sender: event)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailSeque" {
if let detailVC = segue.destination as? DetailViewController {
if let event = sender as? Event {
detailVC.event = event
}
}
}
}
}
我DetailViewController類:
class DetailViewController: UIViewController {
var event: Event!
@IBOutlet weak var eventTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
eventTitle.text = event.title // error here. says event is nil.
}
}
你的故事板是如何連接起來的?它是來自表格單元還是來自主視圖控制器? – dan
@dan它來自我的MainViewController中的表格單元格。 – Jay