在我的应用程序中,我有一个设置 View ,您可以在其中更改应用程序的背景颜色。 我需要一种方法来从一个 View Controller 更改所有 View 的背景颜色。
我该如何实现这一点?
最佳答案
我建议您创建一个单例对象,它将存储应用程序的设置并保存。在此服务中提供一个后台属性,然后您可以在任何地方获取它。
更新:
这是 SettingsService 单例:
import Foundation
import UIKit
class SettingsService {
class var sharedService : SettingsService {
struct Singleton {
static let instance = SettingsService()
}
return Singleton.instance
}
init() { }
var backgroundColor : UIColor {
get {
var data: NSData? = NSUserDefaults.standardUserDefaults().objectForKey("backgroundColor") as? NSData
var returnValue: UIColor?
if data != nil {
returnValue = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as? UIColor
} else {
returnValue = UIColor(white: 1, alpha: 1);
}
return returnValue!
}
set (newValue) {
let data = NSKeyedArchiver.archivedDataWithRootObject(newValue)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "backgroundColor")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
它有一个 backgroundColor 属性,它使用 NSUserDefaults 来存储值并在用户默认值中没有任何值时初始化一个默认值。
现在您可以使用它在设置 View 中设置值:
func backgroundColorChanged(color : UIColor) {
SettingsService.sharedService.backgroundColor = color;
}
并使用它,例如,在 viewDidLoad() 方法中:
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = SettingsService.sharedService.backgroundColor;
}
关于ios - 从一个 View Controller 更改项目中所有 View 的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093226/