当用户按下按钮时,图像会变为开启状态。当用户离开视图控制器时,我需要它记住按钮在下次进入此VC时设置为图像。我试过NSUser默认无效。有人可以帮忙吗?
在按钮操作中:
buttonPressed = !buttonPressed
let defaults = NSUserDefaults.standardUserDefaults()
if buttonPressed == true {
let followedObjectId = userToShowDetail?["name"] as? String
isFollowing[followedObjectId!] = true
sender.setImage(UIImage(named: "fave_on@2x.png"), forState: UIControlState.Normal)
print("follow")
let following = PFObject(className: "Followers")
following["following"] = userToShowDetail?["name"] as? String
following["follower"] = PFUser.currentUser()?.objectId
favLabel.text = "Favourite Jammer"
following.saveInBackground()
defaults.setBool(true, forKey: "SwitchState")
} else {
if buttonPressed != true {
let followedObjectId = userToShowDetail?["name"] as? String
isFollowing[followedObjectId!] = false
print("notFollow")
sender.setImage(UIImage(named: "fave_off@2x.png"), forState: UIControlState.Normal)
favLabel.text = "Add to favourites?"
defaults.setBool(false, forKey: "SwitchState")
在视图中加载:
// save switch state:
let defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("SwitchState") != nil) {
buttonPressed = defaults.boolForKey("SwitchState")
}
答案 0 :(得分:1)
尝试下面的解决方案。每次单击按钮,它都会打开和关闭状态。如果您离开视图控制器,它将保存状态。如果这对您有帮助,请告诉我。
@contextmanager
def make_session_scope(Session):
"""Provide a transactional scope around a series of operations."""
session = Session()
session.expire_on_commit = False
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
with make_session_scope(session) as session:
query = session.query(model)
答案 1 :(得分:0)
您只需在AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{
var myButtonSwitchState: Bool = false
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//your code...
}
//the rest of your code...
}
然后,在您的视图控制器中,您可以通过将UIApplication.sharedApplication().delegate
投射到AppDelegate
var appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
然后,您只需在app delegate
中获取并设置布尔值即可func getSwitchState() -> Bool{
return appDelegate.myButtonSwitchState
}
func setSwitchState(value: Bool){
appDelegate.myButtonSwitchState = value
}
如果您希望在用户退出应用后将此状态存储起来(将其从正在运行的应用中删除),则可以使用NSUserDefaults
而只需使用此代码
func getSwitchState() -> Bool{
return NSUserDefaults.standardUserDefaults().boolForKey("buttonStatus")
}
func setSwitchState(value: Bool){
NSUserDefaults.standardUserDefaults().setObject(value, forKey: "buttonStatus")
NSUserDefaults.standardUserDefaults().synchronize()
}