所以我在 View Controller 上有 4 个按钮,它是应用程序的初始 View Controller。
每个按钮都“显示”到不同的导航 Controller (连接到 UITableView)。
我的目标是以某种方式保存使用 NSUserDefaults 触摸的按钮,并跳过 View Controller 并直接转到选定的导航 Controller ,每次打开应用程序时!这可能吗?
我正在用 Swift 写这个
这是我的 AppDelegate(关于“var buttonSelected”的警告):
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var buttonSelected = NSUserDefaults.standardUserDefaults().integerForKey("buttonSelected")
print("run")
return true
}
}
这是我的 4 个按钮的 View Controller :
import UIKit
class NSUserDefault: UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
var buttonSelected: Int = 0
if (segue.identifier == "button1Segue") {
buttonSelected = 1
}
else if (segue.identifier == "button2Segue") {
buttonSelected = 2
}
else if (segue.identifier == "button3Segue"){
buttonSelected = 3
}
else if (segue.identifier == "button4Segue") {
buttonSelected = 4
}
NSUserDefaults.standardUserDefaults().setInteger(buttonSelected, forKey: "buttonSelected") // Save the selection in user defaults
NSUserDefaults.standardUserDefaults().synchronize() // Save changes
print("runs")
if buttonSelected == 1 {
let welcomeVC: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ONW") as UIViewController
self.parentViewController?.presentViewController(welcomeVC, animated: true, completion: nil)
}
if buttonSelected == 2 {
let welcomeVC: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("OE") as UIViewController
self.parentViewController?.presentViewController(welcomeVC, animated: true, completion: nil)
}
if buttonSelected == 3 {
let welcomeVC: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("OS") as UIViewController
self.parentViewController?.presentViewController(welcomeVC, animated: true, completion: nil)
}
if buttonSelected == 4 {
let welcomeVC: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ON") as UIViewController
self.parentViewController?.presentViewController(welcomeVC, animated: true, completion: nil)
}
}
}
最佳答案
我希望这对你有用
@IBAction func saveButton(sender: UIButton)
{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(true, forKey: "button1")
defaults.synchronize()
}
检查按钮会像这样
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let prefs = NSUserDefaults.standardUserDefaults()
if let prefs.boolForKey("button1") == true {
// here code if button was clicked
} else {
// here code if button was not clicked
}
return true
}
关于ios - 使用 NSUserDefaults 保存 ViewController 页面上的触摸按钮,该按钮与导航 Controller 相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35851128/