ios - 选择表格单元格时应用程序崩溃 Swift

标签 ios swift uitableview swift2 segue

我试图修复它,但是当我登录我的应用程序时,它会转到一个 TableView Controller ,当我单击一个单元格时,它会崩溃并出现“因 NSException 类型的未捕获异常而终止”的错误,它说信号中止,我不知道为什么。非常感谢任何帮助。

项目链接:https://www.dropbox.com/s/1d4d8opuxzpcuk4/TicketekApp.zip?dl=0

代码:

EventTableViewController(源 View Controller ):

//  EventTableViewController.swift



import UIKit

class EventTableViewController: UITableViewController {
// MARK: Properties
var currentlySelectedIndex = 0
var events = [Event]()
var isAdmin: Bool = false
var currentUser: String = ""
override func viewDidLoad() {
    super.viewDidLoad()

    // Use the edit button item provided by the table view controller.
    if isAdmin == true {
    navigationItem.leftBarButtonItem = editButtonItem()
    }
    // Load any saved events, otherwise load sample data.
    if let savedEvents = loadEvents() {
        events += savedEvents
    } else {
        // Load the sample data.
        loadSampleEvents()
    }
}

func loadSampleEvents() {
    let photo1 = UIImage(named: "event1")!
    let event1 = Event(name: "ACDC", photo: photo1, rating: 4, price: 500.0, eventDescription: "Album", album: "Album1")!

    let photo2 = UIImage(named: "event2")!
    let event2 = Event(name: "Cold Play", photo: photo2, rating: 5, price: 500.0, eventDescription: "Album", album: "Album1")!

    let photo3 = UIImage(named: "event3")!
    let event3 = Event(name: "One Direction", photo: photo3, rating: 3, price: 500.0, eventDescription: "Album", album: "Album1")!

    events += [event1, event2, event3]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return events.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "EventTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! EventTableViewCell

    // Fetches the appropriate event for the data source layout.
    let event = events[indexPath.row]

    cell.nameLabel.text = event.name
    cell.photoImageView.image = event.photo
    cell.ratingControl.rating = event.rating
    cell.priceLabel.text = event.album

    return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    //Record the row selected
    currentlySelectedIndex = indexPath.row

    //check for your condition here something like
    if isAdmin {
        performSegueWithIdentifier("eventViewControllerSegue", sender: self)
    } else {
        performSegueWithIdentifier("userEventTableViewControllerSegue", sender: self)
    }
}

// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want item to be editable.
    return true
}


// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        events.removeAtIndex(indexPath.row)
        saveEvents()
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create new instance of  class, add to the array, and add a new row to the table
    }
}


/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/


// MARK: - Navigation

// preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "eventViewControllerSegue"  {
        let eventDetailViewController = segue.destinationViewController as! EventViewController
        //Get the associated event
        eventDetailViewController.event = events[currentlySelectedIndex]
    } else  if segue.identifier == "userEventViewControllerSegue"  {
        let eventDetailViewController = segue.destinationViewController as! UserEventViewController
        //Get the associated event
        eventDetailViewController.event = events[currentlySelectedIndex]
        if let destinationVC = segue.destinationViewController as? UserEventViewController {

            destinationVC.currentUser = currentUser
        }
    }
    else if segue.identifier == "AddItem" {
        print("Adding new event.")
    }
}

@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
    if let sourceViewController = sender.sourceViewController as? EventViewController, event = sourceViewController.event {
        if let selectedIndexPath = tableView.indexPathForSelectedRow {
            // Update an existing event.
            events[selectedIndexPath.row] = event
            tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
        } else {
            // Add a new event.
            let newIndexPath = NSIndexPath(forRow: events.count, inSection: 0)
            events.append(event)
            tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
        }
        // Save the events.
        saveEvents()
    }
}

// MARK: NSCoding

func saveEvents() {
    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(events, toFile: Event.ArchiveURL.path!)
    if !isSuccessfulSave {
        print("Failed to save events...")
    }
}

func loadEvents() -> [Event]? {
    return NSKeyedUnarchiver.unarchiveObjectWithFile(Event.ArchiveURL.path!) as? [Event]
}
}

UserEventViewController(如果 isAdmin 为 false,则为目标 View Controller ):

//  EventViewController.swift



import UIKit

class UserEventViewController: UIViewController {
// MARK: Properties










@IBOutlet weak var eventDescriptionLabel: UITextView!

@IBOutlet weak var priceLabel: UILabel!

@IBOutlet weak var nameLabel: UILabel!

@IBOutlet weak var photoImageView: UIImageView!

@IBOutlet weak var albumNameLabel: UILabel!

@IBOutlet weak var myTitle: UINavigationItem!

@IBOutlet weak var ratingControl: RatingControl!

var event: Event?
var currentUser: String = ""

override func viewDidLoad() {
    super.viewDidLoad()



    // Set up views if editing an existing event.
    if let event = event {
        myTitle.title = event.name
        nameLabel.text   = event.name
        photoImageView.image = event.photo
        ratingControl.rating = event.rating
        eventDescriptionLabel.text = event.eventDescription
        albumNameLabel.text = event.album
        priceLabel.text = String(event.price)
    }
    }





override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "BuyTickets" {
        if let destinationVC = segue.destinationViewController as? seatsPickerViewController{
            destinationVC.price = event!.price
            destinationVC.name = event!.name
            destinationVC.album = event!.album
            destinationVC.photo = event!.photo
            destinationVC.currentUser = currentUser
        }
                }

}


}

EventViewController(目标 View Controller ,如果 isAdmin 为真):

//  EventTableViewController.swift



import UIKit

class EventTableViewController: UITableViewController {
// MARK: Properties
var currentlySelectedIndex = 0
var events = [Event]()
var isAdmin: Bool = false
var currentUser: String = ""
override func viewDidLoad() {
    super.viewDidLoad()

    // Use the edit button item provided by the table view controller.
    if isAdmin == true {
    navigationItem.leftBarButtonItem = editButtonItem()
    }
    // Load any saved events, otherwise load sample data.
    if let savedEvents = loadEvents() {
        events += savedEvents
    } else {
        // Load the sample data.
        loadSampleEvents()
    }
}

func loadSampleEvents() {
    let photo1 = UIImage(named: "event1")!
    let event1 = Event(name: "ACDC", photo: photo1, rating: 4, price: 500.0, eventDescription: "Album", album: "Album1")!

    let photo2 = UIImage(named: "event2")!
    let event2 = Event(name: "Cold Play", photo: photo2, rating: 5, price: 500.0, eventDescription: "Album", album: "Album1")!

    let photo3 = UIImage(named: "event3")!
    let event3 = Event(name: "One Direction", photo: photo3, rating: 3, price: 500.0, eventDescription: "Album", album: "Album1")!

    events += [event1, event2, event3]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return events.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "EventTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! EventTableViewCell

    // Fetches the appropriate event for the data source layout.
    let event = events[indexPath.row]

    cell.nameLabel.text = event.name
    cell.photoImageView.image = event.photo
    cell.ratingControl.rating = event.rating
    cell.priceLabel.text = event.album

    return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    //Record the row selected
    currentlySelectedIndex = indexPath.row

    //check for your condition here something like
    if isAdmin {
        performSegueWithIdentifier("eventViewControllerSegue", sender: self)
    } else {
        performSegueWithIdentifier("userEventTableViewControllerSegue", sender: self)
    }
}

// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want item to be editable.
    return true
}


// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        events.removeAtIndex(indexPath.row)
        saveEvents()
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create new instance of  class, add to the array, and add a new row to the table
    }
}


/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/


// MARK: - Navigation

// preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "eventViewControllerSegue"  {
        let eventDetailViewController = segue.destinationViewController as! EventViewController
        //Get the associated event
        eventDetailViewController.event = events[currentlySelectedIndex]
    } else  if segue.identifier == "userEventViewControllerSegue"  {
        let eventDetailViewController = segue.destinationViewController as! UserEventViewController
        //Get the associated event
        eventDetailViewController.event = events[currentlySelectedIndex]
        if let destinationVC = segue.destinationViewController as? UserEventViewController {

            destinationVC.currentUser = currentUser
        }
    }
    else if segue.identifier == "AddItem" {
        print("Adding new event.")
    }
}

@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
    if let sourceViewController = sender.sourceViewController as? EventViewController, event = sourceViewController.event {
        if let selectedIndexPath = tableView.indexPathForSelectedRow {
            // Update an existing event.
            events[selectedIndexPath.row] = event
            tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
        } else {
            // Add a new event.
            let newIndexPath = NSIndexPath(forRow: events.count, inSection: 0)
            events.append(event)
            tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
        }
        // Save the events.
        saveEvents()
    }
}

// MARK: NSCoding

func saveEvents() {
    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(events, toFile: Event.ArchiveURL.path!)
    if !isSuccessfulSave {
        print("Failed to save events...")
    }
}

func loadEvents() -> [Event]? {
    return NSKeyedUnarchiver.unarchiveObjectWithFile(Event.ArchiveURL.path!) as? [Event]
}
}

控制台输出:

2015-11-27 22:10:15.492 TicketekApp[14326:6837851] - 在仅变换层中更改属性 masksToBounds,将无效 2015-11-27 22:10:15.493 TicketekApp[14326:6837851] - 在仅变换层中更改属性 masksToBounds,将无效 2015-11-27 22:10:15.494 TicketekApp[14326:6837851] - 在仅变换层中更改属性 masksToBounds,将无效 2015-11-27 22:10:37.900 TicketekApp[14326:6837851] * 由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'Receiver () 没有带有标识符 'userEventTableViewControllerSegue' 的 segue * 首先抛出调用栈: ( 0 CoreFoundation 0x00251a94 异常预处理 + 180 1 libobjc.A.dylib 0x0208fe02 objc_exception_throw + 50 2 UIKit 0x00e33960 -[UIViewController shouldPerformSegueWithIdentifier:sender:] + 0 3 TicketekApp 0x00023448 _TFC11TicketekApp24EventTableViewController9tableViewfS0_FTCSo11UITableView23didSelectRowAtIndexPathCSo11NSIndexPath_T_ + 424 4 TicketekApp 0x000234e9 _TToFC11TicketekApp24EventTableViewController9tableViewfS0_FTCSo11UITableView23didSelectRowAtIndexPathCSo11NSIndexPath_T_ + 89 5 UIKit 0x00dd5b79 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1915 6 UIKit 0x00dd5dd0 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 381 7 UIKit 0x00ddbff5 __38-[UITableView touchesEnded:withEvent:]_block_invoke + 57 8 UIKit 0x00c7c37b _runAfterCACommitDeferredBlocks + 337 9 UIKit 0x00c90839 _cleanUpAfterCAFlushAndRunDeferredBlocks + 103 10 UIKit 0x00c9e4db _afterCACommitHandler + 102 11 核心基础 0x0016b77e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 30 12 核心基础 0x0016b6de __CFRunLoopDoObservers + 398 13 核心基础 0x0016105c __CFRunLoopRun + 1340 14 核心基础 0x00160866 CFRunLoopRunSpecific + 470 15 核心基础 0x0016067b CFRunLoopRunInMode + 123 16 图形服务 0x044c7664 GSEventRunModal + 192 17 图形服务 0x044c74a1 GSEventRun + 104 18 UIKit 0x00c6ecc1 UIApplicationMain + 160 19 TicketekApp 0x000266cc 主 + 140 20 libdyld.dylib 0x02b00a21 开始 + 1 ) libc++abi.dylib:以 NSException 类型的未捕获异常终止 (lldb)

最佳答案

你需要改变下面的东西,因为你提到了错误的标识符,而且这个类必须有父类作为 UINavigationController

performSegueWithIdentifier("userEventTableViewControllerSegue", sender: self)

performSegueWithIdentifier("userEventViewControllerSegue", sender: self)

关于ios - 选择表格单元格时应用程序崩溃 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33958089/

相关文章:

ios - UITextView 限制字符数和剩余显示数

ios - 无法打开谷歌地图

swift - 如何将.ply、.STL、.dae文件转换为苹果SceneKit框架支持的.scn文件格式?

ios - 如何在表格 View 中展开和折叠多行和子行

ios - OperationQueue 执行时未调用操作子类 "main"方法?

ios - 使用分段控制操作调用 subview Controller ?

objective-c - UItable 单元格溢出 ios

ios - 根据 iOS 中的位置对 UIView subview 进行 x 顺序排序

ios - 以编程方式添加到 View Controller 的 UITableView 不会填充

ios - 字母滚动条不显示