2015-09-04 31 views
0

我有一個沒有segue的靜態單元格表​​視圖。這與iPhone設置 - >聲音 - >文本色調相同。實現複選標記並從另一個ViewController播放系統聲音沒有任何問題。當返回聲音設置ViewController時,沒有複選標記。我將用戶默認保存indexPath.row和indexPath.section。我正在檢索它並將它們存儲在變量中。如何使用這些現在具有indexPath的變量「one for row and one for section」來指示先前選擇的行。我已經嘗試過在網絡,視頻和StackoverFlow上的解決方案,我似乎無法得到這個。複選標記在返回到tableview時消失

var rowSelected:Int = 0 
var rowSection:Int = 0 

override func viewDidLoad() { 
    super.viewDidLoad() 
    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() 

    if let soundIsNotNill = defaults.objectForKey("rowSelectedKey") as? Int{ 
     self.rowSelected = defaults.objectForKey("rowSelectedKey") as! Int} 

    if let soundIsNotNill = defaults.objectForKey("rowSectionKey") as? Int{ 
     self.rowSection = defaults.objectForKey("rowSectionKey") as! Int} 

} 

override func viewWillAppear(animated: Bool) { 
    println(" VDL rowSelected \(rowSelected)") 
    println(" VDL rowSection \(rowSection)") 

} 

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

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

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    let tappedItem = indexPath.row 
     rowSelected = tappedItem 
    let section  = indexPath.section 
     rowSection = section 

    for row in 0..<13 { 
     if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) { 
       cell.accessoryType = row == tappedItem ? .Checkmark : .None 
     } 
    } 



    println("didSelectRow rowSelected \(rowSelected)") 
    println("didSelectRow rowSection \(rowSection)") 

    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() 
     defaults.setObject(section, forKey: "rowSectionKey") 
     defaults.setObject(tappedItem, forKey: "rowSelectedKey") 
     defaults.synchronize() 

    saveSound() 
} 
+0

我看到restorationIdentifier是如何工作的,但不知道如何在上面的ViewController中實現它。我是新來的。我有一種方法來使用表視圖單元格標識符告訴tableview「willDisplayCell」或適當的「tableView(tableView:UITableView」使用保存在變量中的行和部分來添加複選標記嗎? – Dan

回答

0

保留表的選擇狀態的一種方法是給它一個恢復標識符字符串。您可以通過設置表視圖的restorationIdentifier屬性或將其設置在Interface Builder中的表的身份檢查器中執行此操作。