我已經構建了一個名爲Mad Lib的簡單應用程序。在這裏你輸入一個單詞11次到文本框中。單詞被附加到名爲wordStack的列表中。你點擊OK按鈕,準備讓segway把用戶帶到第二個屏幕。在這裏,這11個單詞被作爲字符串填充到文本中。如何通過在NsUserDefaults中將數據保存爲數組來記住遊戲狀態
的第二頁上的txt例:「泰山也被稱爲(wordStack [1])」
所以,我讀似乎訪問屬性的用戶默認當內容是不變的,也很用於簡單數據如單個字符串或可能是一個整數。我有一個很難得到這個與這個數組一起工作。
所以還挺除了事實
var wordStack: [String] = []
復位workstack每次工作。
任何幫助我解決問題的解決方案都是絕對的英雄!謝謝!
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let s = userDefault.valueForKey("wordstack"){
var wordStack: [String] = []
for i in s as! NSArray {
print(i)
wordStack.append(String(i))
print(wordStack)
}
}
print(wordStack)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var guess: UILabel!
@IBOutlet weak var textField: UITextField!
// Save game state.
var userDefault = NSUserDefaults.standardUserDefaults()
// Saves the user's input.
var wordStack: [String] = []
func test() {
let userInput = textField.text
textField.text = nil
if wordStack.count < 10 {
wordStack.append(userInput!)
guess.text = "\(11-wordStack.count) guesses left!"
userDefault.setValue(wordStack, forKey: "wordstack")
} else {
wordStack.append(userInput!)
}
}
// When pressed enter in the textfield append the input to workstack and refresh textfield for new input.
@IBAction func enterTextField(sender: AnyObject) {
test()
}
@IBAction func buttonClick(sender: AnyObject) {
if wordStack.count <= 10 {
let alertController = UIAlertController(title: "Wacht", message: "Je bent nog niet klaar. \(wordStack.count)/11 woorden ingevuld.",preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController,animated: true, completion: nil)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let secondViewController: ViewController2 = segue.destinationViewController as! ViewController2
if wordStack.count > 10 {
secondViewController.outputMessage = "One of the most silly characters is named Tarzan of the bees. Tarzan is raised by an/a \(wordStack[0]) and lives in the \(wordStack[1]) in the heart of the darkest \(wordStack[2]). He spent most of his time eating \(wordStack[3]) and swinging from tree to \(wordStack[4]). Whenever he gets angry he beats on his chest and says \(wordStack[5])! This is his way cry. Tarzan always dresses in smelly \(wordStack[6]) shorts made of the skin of an/a \(wordStack[7]) and his best friend is an/a \(wordStack[8]) Chimpanzee called Cheetah. He is supposed to be able to speak to elephants and \(wordStack[9]). In the movies, Tarzan plays \(wordStack[10])"
// reset guesses
//var count: Int = 0
}
}
}
究竟是什麼問題。你沒有達到在NSUserDefaults中存儲和檢索你的數組? – LastMove