swift splitview 控制器默认单元格

swift splitview controller default cell

我目前正在使用 xcode6 中的 swift 进行拆分视图控制器的项目。

我目前拥有它,因此当应用程序加载时,它会记住您之前选择的单元格并将 "select" 该单元格。 However when the cell is selected it doesn't initiate the segue to the detail view controller loading that cells related information.

这是我的主视图控制器代码,想知道我可以添加什么来在应用程序加载时为选定的单元格启动 segue?

class MasterViewController: UITableViewController {

var detailViewController: DetailViewController? = nil
var titles = [String]()
var ageGroups = [String]()
var danceForms = [String]()
var danceDivisions = [String]()
var danceCategories = [String]()
var routineIds = [Int]()



override func awakeFromNib() {
    super.awakeFromNib()
    self.clearsSelectionOnViewWillAppear = false
    self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}

override func viewDidLoad() {
    super.viewDidLoad()
   self.navigationItem.setRightBarButtonItems([rightAddBarButtonItem,rightSearchBarButtonItem], animated: true)





    let query = PFQuery(className: "Schedule")
    query.orderByAscending("routineId")
    query.whereKey("eventId", equalTo: 16)
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if let objects = objects {


            for object in objects {

                self.titles.append(object["title"] as! String)
                self.ageGroups.append(object["ageGroup"] as! String)
                self.danceForms.append(object["danceForm"] as! String)
                self.danceDivisions.append(object["danceDivision"] as! String)
                self.danceCategories.append(object["danceCategory"] as! String)
                self.routineIds.append(object["routineId"] as! Int)



                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.tableView.reloadData()
                    var returnValue: Int? = NSUserDefaults.standardUserDefaults().objectForKey("selectedCell") as? Int
                    if let value = returnValue{

                    }
                    else{
                        returnValue = 1;
                    }
                    if  returnValue! > self.routineIds.count{
                        returnValue = 1;
                    }
                    let rowToSelect:NSIndexPath = NSIndexPath(forRow: returnValue!-1, inSection: 0);  //slecting 0th row with 0th section
                    self.tableView.selectRowAtIndexPath(rowToSelect, animated: true, scrollPosition: UITableViewScrollPosition.None);

                })




            }


        }
    }







}

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


// MARK: - Segues


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "showDetail" {
        if let indexPath = self.tableView.indexPathForSelectedRow() {
            let object = routineIds[indexPath.row] as Int
            let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
            controller.detailItem = object
            controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
            controller.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

// MARK: - Table View

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

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

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("scheduleCell", forIndexPath: indexPath) as! scheduleCell

    var myCustomSelectionColorView = UIView()
    myCustomSelectionColorView.backgroundColor = UIColor.whiteColor()
    cell.selectedBackgroundView = myCustomSelectionColorView



    cell.routineId.text = "\(routineIds[indexPath.row])"
    cell.routineTitle.text = titles[indexPath.row]
    cell.routineAgeGroup.text = " - \(ageGroups[indexPath.row])"
    cell.routineDanceForm.text = " - \(danceForms[indexPath.row])"
    cell.routineDivision.text = danceDivisions[indexPath.row]
    cell.routineCategory.text = danceCategories[indexPath.row]

    return cell
}

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.

    return false
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(routineIds[indexPath.row])
    NSUserDefaults.standardUserDefaults().setInteger(routineIds[indexPath.row], forKey: "selectedCell")
    NSUserDefaults.standardUserDefaults().synchronize()
    var returnValue: Int? = NSUserDefaults.standardUserDefaults().objectForKey("selectedCell") as? Int
    if returnValue! == 1{

    }

    println(returnValue)

}

您可以使用 UIViewController 上的 performSegueWithIdentifier 方法手动启动 segue。

// in your dispatch_async block:
self.performSegueWithIdentifier("showDetail", self)

另一种方法是利用state restoration。好处是应用程序可以恢复每个视图控制器的状态,而无需您编写代码或处理您现在正在做的大部分事情。

状态恢复将为您保存和加载应用程序状态,使您不必在 NSUserDefaults 中保留详细信息,例如选择了哪个单元格。 SDK 实际上保留了很多有用的细节,比如你的 splitViewController 是折叠还是展开,导航栏是紧凑还是隐藏等等。这些都是很好的细节,当你使用状态恢复。

要利用状态恢复,您需要:

  1. 让你的AppDelegate实现application:shouldSaveApplicationState:application:shouldRestoreApplicationState:

  2. 为每个要保留的视图控制器分配恢复标识符。您可以在 Storyboard 中轻松执行此操作。

  3. 显示您的应用 window 来自 application:willFinishLaunchingWithOptions:

  4. 使用encodeRestorableStateWithCoder:decodeRestorableStateWithCoder:

  5. 对视图控制器的状态进行编码和解码

另一个好处是视图控制器可以保存它自己的关于它正在显示的对象的详细信息,而无需另一个视图控制器执行任何 segue(或传递任何详细信息)。它允许您的视图控制器更加独立,并且与其他视图控制器的耦合度降低。

状态恢复确实减少了您必须编写的代码量,这在长期 运行 需要维护、支持和升级应用程序方面是有回报的。