首页 > 解决方案 > 使用 userDefaults 保存自定义背景颜色

问题描述

我创建了一个带有一些按钮的网格,每个按钮都与某种颜色相关联并更改视图的背景颜色:

 @IBOutlet weak var backgroundSelectionView: UIView!
 override func viewDidLoad() {
        super.viewDidLoad()

      backgroundSelectionView.isHidden = true
        backgroundSelectionView.isUserInteractionEnabled = false
        backgroundGrid()
    }
@IBAction func backgroundColor(_ sender: Any) {
        if backgroundSelectionView.isHidden == true {
            backgroundSelectionView.isHidden = false
            backgroundSelectionView.isUserInteractionEnabled = true
        } else {
            backgroundSelectionView.isHidden = true
            backgroundSelectionView.isUserInteractionEnabled = false
        }
    }
    func backgroundGrid(){
       blackButtonOutlet.layer.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        blackButtonOutlet.layer.borderWidth = 1
        blackButtonOutlet.layer.borderColor = UIColor.black.cgColor
    }
    @IBOutlet weak var blackButtonOutlet: UIButton!

    @IBAction func blackButton(_ sender: Any) {
       view.layer.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)

    }

现在它工作正常,如果我按下按钮,它会设置背景,一切看起来都很好。唯一的问题是,当我在应用程序中导航或离开时,背景再次变为白色(默认)。我想用 userDefaults 设置它,我该怎么做?

标签: iosswiftcocoa-touchnsuserdefaults

解决方案



推荐阅读