【问题标题】:Saving custom background color with userDefaults [duplicate]使用 userDefaults 保存自定义背景颜色 [重复]
【发布时间】:2019-08-05 21:18:40
【问题描述】:

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

 @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 设置它,我该怎么做?

【问题讨论】:

  • Saving UIColor to and loading from NSUserDefaults... 无论如何:IBAction 中的逻辑可以简化为:@IBAction func backgroundColor(_ sender: Any) { backgroundSelectionView.isHidden.toggle() backgroundSelectionView.isUserInteractionEnabled.toggle() }
  • 另外你根本不需要设置isUserInteractionEnabled,因为如果视图被隐藏了,用户就不能与之交互

标签: ios swift cocoa-touch nsuserdefaults


【解决方案1】:

我没有看到其他按钮以及您更改背景颜色的位置,但假设您使用的是颜色的 HeX 表示,ypu 可以将背景颜色保存在共享首选项中,并始终使用共享状态来设置背景。

当您想将颜色保存到用户首选项时UserDefaults.standard.set("#FF2200", forKey: "background_color_hex")

要从首选项中检索背景颜色的十六进制表示let hexBackgroundColor = UserDefaults.standard.string(forKey: “background_color_hex”) ?? “#FFFFFF”.

然后要使用它,您可以拥有一个扩展来获得基于其十六进制表示的 UIColor,就像许多在线文章中解释的那样,例如这个https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor像这样: view.backgroundColor = UIColor(hex: hexBackgroundColor)

我猜可能还有很多其他的解决方案,这个是我想到的最快的一个。

【讨论】:

  • 我正在使用颜色文字,当我按下 blackButton 时我改变了背景
  • 我看不出其中的原因,因为在我看来,这使得在您的应用程序和您将来可能拥有的其他堆栈(android、ios、web)中管理颜色和主题变得更加复杂。但是,无论我不知道您有什么好的理由,您都可以将红色、绿色、蓝色、alpha 的 4 个值保存在共享首选项中并检索它们。或者可以将它们保存为连接它们的一个字符串,然后在从 prefs 检索字符串时从字符串中提取它。 store some value in user default, retrieve it, use it.
  • 您总是使用文字将背景颜色设置为#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),而不是使用不同的红色、绿色、蓝色、alpha 值。每当您更改背景颜色时,设置不同的值,然后将它们存储在用户默认值中。然后在您的viewDidLoad 中,您可以从用户默认值中检索值并使用从User Defaults 检索到的值设置背景
猜你喜欢
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多