将分段控件的选择保存到NSuserdefaults

时间:2016-08-12 06:30:41

标签: ios swift nsuserdefaults uisegmentedcontrol

我使用分段控件作为简单的是或否按钮。我想通过使用NSuserdefaults更改视图后保存选择的结果,分段控件只有两个选项"是"或"不"我现在有这个

class DetailContactViewController: UIViewController {

@IBOutlet var attendingAnswer: UISegmentedControl!
@IBOutlet var name : UILabel!
@IBOutlet weak var contactImage: UIImageView!
@IBOutlet weak var email: UILabel!

@IBOutlet weak var attending : UILabel!
var contact : CNContact?
var defaults : NSUserDefaults  =  NSUserDefaults.standardUserDefaults()

override func viewDidLoad() {
    super.viewDidLoad()
    let formatter = CNContactFormatter()

    if let contact = contact {

        name.text =  (contact.phoneNumbers.first?.value as! CNPhoneNumber).stringValue
        email.text = (contact.emailAddresses.first?.value as? String)
        defaults.setValue(true, forKey: name.text!)
       defaults.valueForKey(name.text!)

    }

    // Do any additional setup after loading the view.

}

1 个答案:

答案 0 :(得分:1)

@IBAction func segmentedControlAction(sender: AnyObject) {
    if(segementControl.selectedSegmentIndex == 0)
    {
        let segmentControl = NSUserDefaults.standardUserDefaults()
        segmentControl.setBool(true, forKey: "KeyName")
    }
    else if(segementControl.selectedSegmentIndex == 1)
    {
        let segmentControl = NSUserDefaults.standardUserDefaults()
        segmentControl.setBool(false, forKey: "KeyName")

    }

    //Fetch 
    let defaults = NSUserDefaults.standardUserDefaults()
    let segementName = defaults.boolForKey("KeyName")
}