我在使用NSUserDefaults在Swift中創建書籤列表在tableView中遇到了一些麻煩。保存和顯示部分我有,但刪除保存的字符串和從另一個視圖控制器重新加載tableView是我被困在很長一段時間。保存並從一個ViewController刪除NSUserDefaults到另一個 - Swift 2
基本上,我只是想用一個按鈕保存一個字符串到tableView中的另一個視圖控制器。當選擇按鈕時,將字符串保存到tableView。當按鈕取消選擇時,從tableView中刪除相同的字符串。
收藏 - 視圖 - 控制器
import UIKit
class BookmarkController: UIViewController {
var bookmark: String = "Hello World"
@IBOutlet var myButton: UIButton!
@IBAction func buttonAction(sender: UIButton!) {
if myButton.backgroundColor == UIColor.grayColor() {
myButton.backgroundColor = UIColor.blueColor()
favoritesList.append(bookmark)
NSUserDefaults.standardUserDefaults().setObject(favoritesList, forKey:"favoritesList")
NSUserDefaults.standardUserDefaults().synchronize()
}
else if myButton.backgroundColor == UIColor.blueColor() {
myButton.backgroundColor = UIColor.grayColor()
NSUserDefaults.standardUserDefaults().removeObjectForKey("favoritesList")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
override func viewDidLoad() {
super.viewDidLoad()
if (NSUserDefaults.standardUserDefaults().objectForKey("favoritesList") != nil) {
myButton.backgroundColor = UIColor.blueColor()
}else{
myButton.backgroundColor = UIColor.grayColor()
}
}
}
視圖控制器具有的tableView(保持數據)
import UIKit
var favoritesList = [String]()
class SecondViewController: UIViewController, UITableViewDelegate {
@IBOutlet var toDoListTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
if NSUserDefaults.standardUserDefaults().objectForKey("favoritesList") != nil {
favoritesList = NSUserDefaults.standardUserDefaults().objectForKey("favoritesList") as! [String]
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return favoritesList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel!.font = UIFont.systemFontOfSize(14.0)
cell.textLabel!.numberOfLines = 0
cell.textLabel!.text = favoritesList[indexPath.row]
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
if editingStyle == UITableViewCellEditingStyle.Delete{
favoritesList.removeAtIndex(indexPath.row)
NSUserDefaults.standardUserDefaults().setObject(favoritesList, forKey: "favoritesList")
toDoListTable.reloadData()
}
override func viewDidAppear(animated: Bool) {
toDoListTable.reloadData()
}
}
如果你有'if(true){set - > sync()} else {set - > sync()}',你應該把它改爲if(true){set} else {set} sync ()' - 清潔代碼 – iSkore
不知道這是否真的是你的問題,但我注意到的一件事是你正在刪除洞列表? 'NSUserDefaults.standardUserDefaults()。removeObjectForKey(「favoritesList」)''而不僅僅是按鈕的值? – Lucho
不需要強制同步 –