当我尝试访问时,我使用UserDefaults设置的字符串为nil

时间:2016-11-01 08:27:05

标签: ios swift label nsuserdefaults textfield

main.storyboard

正如下面的代码所示......

当我按下保存按钮时,它会将文本字段输入保存到用户默认值,以便我可以在标签中显示它。这很好用,因为当我保存输入时会立即显示标签。

我添加了一个滑动手势来翻转包含标签的UIView并显示另一个图像。但是当我想用滑动将其翻转时,它会显示一个错误,说标签现在为零?

我是新手,如果这是一个容易修复的容易愚蠢的错误,请不要理我。

Thnx可以提供任何帮助。

ViewController.swift文件

  import UIKit

class ViewController: UIViewController {

var back: UIImageView!

@IBOutlet weak var plateView: UIView!
@IBOutlet weak var text: UITextField!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var saveBtn: UIButton!

var showingFront = true

let defaults = UserDefaults.standard

override func viewDidLoad() {
    super.viewDidLoad()

    back = UIImageView(image: UIImage(named: "back.png"))

    let swipe = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swiped))
    swipe.direction = UISwipeGestureRecognizerDirection.left
    plateView.addGestureRecognizer(swipe)

    label.backgroundColor = UIColor(patternImage: UIImage(named: "blank.png")!)

    saveBtn.isHidden = true

}


func swiped() {

    if (showingFront) {

        UIView.transition(from: label, to: back, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)

        showingFront = false

    } else {


        UIView.transition(from: back, to: label, duration: 1, options: UIViewAnimationOptions.transitionFlipFromLeft, completion: nil)

        showingFront = true

    }
}


@IBAction func editingDidBegin(_ sender: Any) {

    saveBtn.isHidden = false
    label.isHidden = true
    text.isHidden = false
}

@IBAction func save(_ sender: Any) {

    defaults.set(text.text, forKey: "number")
    defaults.synchronize()
    let num = defaults.string(forKey: "number")
    label.text = num

    label.isHidden = false
    saveBtn.isHidden = true

    view.endEditing(true)

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

1 个答案:

答案 0 :(得分:0)

我认为你的代码现在只是一个测试。

尝试同步userDefaults,以便它们由系统编写:

$ rvm --default use 2.3.1

此外,defaults.set(text.text, forKey: "number") defaults.synchronize() ... 返回一个可选项,因为它可能由于多种原因而失败。

defaults.string(forKey: ...)