xcode 保存 UIButton 的状态(复选框) - Swift

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28546557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:39:33  来源:igfitidea点击:

Saving state of UIButton (checkbox) - Swift

iosxcodeswiftuibuttonnsuserdefaults

提问by JohnJLilley

I'm a new developer and I'm making a to-do list app in Swift. I was able to figure out how to change the state of the UIButton(checkbox) on clicking. At the moment I'm trying to figure out how to save that state for when I exit the app or switch views and return. I was able to successfully save the text (to-do list tasks) by using NSUserDefaultsand have also experimented with it on my buttons but cannot figure out how to get it to work.

我是一名新开发人员,我正在 Swift 中制作一个待办事项列表应用程序。我能够弄清楚如何UIButton在单击时更改(复选框)的状态。目前,我正试图弄清楚如何在退出应用程序或切换视图并返回时保存该状态。我能够通过使用成功保存文本(待办事项列表任务),NSUserDefaults并且还在我的按钮上对其进行了试验,但无法弄清楚如何让它工作。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var myButton: Qbutton!

override func viewDidLoad() {
    super.viewDidLoad()

    var isChecked = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked") // here we obtain the last state of the button
    myButton.isChecked = isChecked
    self.view.addSubview(myButton)

I have the UIButtonin a subclass of QButton.

UIButtonQButton.

class Qbutton: UIButton {

    var isSelected: Bool = defaults.boolForKey("isButtonChecked")

    // Images
    let selectedImage = UIImage(named: "Selected")
    let unselectedImage = UIImage(named: "Unselected")


    //Bool Property
    var isChecked:Bool = false{
        didSet{
            if isChecked == true{
                self.setImage(selectedImage, forState: UIControlState.Normal)
            }else{
                self.setImage(unselectedImage, forState: UIControlState.Normal)
            }
            defaults.setObject(isChecked, forKey: "isButtonChecked")
        }
    }

    override init(frame: CGRect){
    super.init(frame:frame)
    self.layer.masksToBounds = true
    self.setImage(unselectedImage, forState: UIControlState.Normal)

    self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    self.isChecked = false
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

func buttonClicked(sender: UIButton) {
    if(sender == self){
        if isChecked == true{
            isChecked = false
        }else{
            isChecked = true
        }
    }
}
}

回答by mauricioconde

well i think you can save the state of the UIButtonwith the NSUserDefaultsjust when the variable isChecked is changed. Something like this:

嗯,我想你可以保存的状态UIButtonNSUserDefaults刚当变量是器isChecked改变。像这样的东西:

var isChecked:Bool = false{
    didSet{
        if isChecked {
            self.setImage(selectedImage, forState: UIControlState.Normal)
        }else{
            self.setImage(unselectedImage, forState: UIControlState.Normal)
        }
        NSUserDefaults.standardUserDefaults().setObject(isChecked, forKey: "isBtnChecked")
        // this method is automatically invoked at periodic intervals, but
        //if you cannot wait for the automatic synchronization you can invoke it
        NSUserDefaults.standardUserDefaults().synchronize() 
    }


}

Now when your app is launched you can check the last state of the UIButtonwith this:

现在,当您的应用程序启动时,您可以使用以下命令检查的最后状态UIButton

var isSelected: Bool = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked")

UPDATE

更新

I made an example using your Qbuttonclass. I hope this can help you:

我用你的Qbutton课做了一个例子。我希望这可以帮助你:

import Foundation
import UIKit

class Qbutton: UIButton {

    // Images
    let selectedImage = UIImage(named: "Selected")
    let unselectedImage = UIImage(named: "Unselected")

    //Bool Property
    var isChecked:Bool = false{
        didSet{
            if isChecked {
                self.setImage(selectedImage, forState: UIControlState.Normal)
            }else{
                self.setImage(unselectedImage, forState: UIControlState.Normal)
            }
            NSUserDefaults.standardUserDefaults().setObject(isChecked, forKey: "isBtnChecked")
            // this method is automatically invoked at periodic intervals, but
            //if you cannot wait for the automatic synchronization you can invoke it
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    override init(frame: CGRect){
        super.init(frame:frame)
        self.layer.masksToBounds = true
        self.setImage(unselectedImage, forState: UIControlState.Normal)

        self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
        self.isChecked = false
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func buttonClicked(sender: UIButton) {
        if(sender == self){
            if isChecked == true{
                isChecked = false
                self.setImage(unselectedImage, forState: UIControlState.Normal)
            }else{
                isChecked = true
                self.setImage(selectedImage, forState: UIControlState.Normal)
            }
        }
    }
}

Now in the UIViewControlleri create a Qbuttonand before i add it to the UIViewControllerview i read the last state of the variable "isBtnChecked".

现在在UIViewController我创建一个Qbutton并在我将它添加到UIViewController视图之前我读取了变量“isBtnChecked”的最后状态。

From the official docs:

来自官方文档

If a boolean value is associated with defaultName in the user defaults, that value is returned. Otherwise, NO is returned.

如果布尔值与用户默认值中的 defaultName 相关联,则返回该值。否则,返回 NO。

import UIKit
class ViewController: UIViewController {
    var myButton: Qbutton!

    override func viewDidLoad() {
        super.viewDidLoad()

        myButton = Qbutton(frame: CGRectMake(100,100,50 ,50));
        var isChecked = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked") // here we obtain the last state of the button
        myButton.isChecked = isChecked // we set the value
        self.view.addSubview(myButton)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

UPDATE 2

更新 2

Here is an example using the selected property of UIButton

这是一个使用 selected 属性的示例 UIButton

import Foundation
import UIKit

class Qbutton: UIButton {

    // Images
    let selectedImage = UIImage(named: "Selected")
    let unselectedImage = UIImage(named: "Unselected")


    //Bool Property
    override var selected: Bool{
        didSet{
            if selected {
                self.setImage(selectedImage, forState: UIControlState.Normal)
            }else{
                self.setImage(unselectedImage, forState: UIControlState.Normal)
            }
            NSUserDefaults.standardUserDefaults().setObject(selected, forKey: "isBtnChecked")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    override init(frame: CGRect){
        super.init(frame:frame)
        self.layer.masksToBounds = true
        self.setImage(unselectedImage, forState: UIControlState.Normal)

        self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
   }

    func buttonClicked(sender: UIButton) {
        self.selected = !self.selected
    }
}

And the UIViewController:

UIViewController

import UIKit
class ViewController: UIViewController {
    var myButton: Qbutton!

    override func viewDidLoad() {
        super.viewDidLoad()

        myButton = Qbutton(frame: CGRectMake(100,100,50 ,50));
        myButton.selected = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked") // here we obtain the last state of the button
        self.view.addSubview(myButton)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

I hope this really can help you!

我希望这真的可以帮助你!

回答by Scott

I think you are completely over-thinking it and making it complicated. Since it's just a simple button the easiest way to do it is set a bool through an IBAction. Let me know if I'm missing something from your question though.

我认为你完全是过度思考并使它变得复杂。由于它只是一个简单的按钮,因此最简单的方法是通过IBAction. 如果我从你的问题中遗漏了什么,请告诉我。

In Objective-C it would be something like this..

在Objective-C中它会是这样的..

{
    BOOL _isStateEnabled;
}

-(IBAction)clickedButton: (id)sender {
    _isStateEnabled = !_isStateEnabled;
}

In Swift I'm not fluent but, something like this..

在斯威夫特我不流利,但是,像这样的..

{
    let _isStateEnabled as boolean;
}

func buttonClicked(sender: UIButton) {
    _isStateEnabled = !_isStateEnabled;
}