0

在这个应用程序中,我希望允许用户更改主菜单的背景颜色。在 MenuVC 中,用户将单击标有“选择颜色”的按钮。'ColorPickerVC' 将以模态方式从 XIB 文件中呈现。

我为此创建了一个 @IBAction 并包含以下代码:

 @IBAction func colorPickerPressed = (_ sender: Any) {   
        let colorPicker = ColorPickerVC()
        colorPicker.modalPresentationStyle = .custom
        present(colorPicker, animated: false, completion: nil)
    }

颜色选择器从 XIB 文件模态加载并以网格格式显示 9 种颜色(UIButton)。

当用户点击一种颜色时,ColorPickerVC 的背景会变为该颜色:

@IBAction func tile1(_ sender: Any) {
        view.backgroundColor = tile1Color.backgroundColor

然后用户点击“确认”按钮,这会关闭视图并返回到 MenuVC:

@IBAction func confirmBtnPressed(_ sender: Any) {
        dismiss(animated: false, completion: nil)
}

这是我正在努力解决的问题:在“ConfirmBtnPressed”操作期间,我希望 MenuVC 背景颜色也更改为 ColorPickerVC 背景(用户之前选择的颜色)

关于如何实现这一目标的任何想法?

谢谢,斯科特

4

2 回答 2

0

最简单的方法……</p>

当用户选择一种颜色时,将该颜色保存为用户默认值(因此它将持续存在而不是一种单一的颜色)。

在菜单 VCviewWillAppear中,从用户默认值中读取颜色。

通常,您会为这种事情使用委托协议,但鉴于它只是一种颜色,并且可能需要记住该颜色,用户默认值是更简单的路线(因为您必须在某个时候将颜色保存在那里并阅读它也退出了)

于 2017-11-20T15:35:40.447 回答
0

您应该了解委托模式:

首先创建一个定义所需功能的协议:

protocol ColorPickerProtocol: class {
    func didSelectColor(_ color: UIColor)
}

使用该协议扩展您的 ViewController 并实现该方法:

class BackgroundColorViewController: UIViewController, ColorPickerProtocol {
    func didSelectColor(_ color: UIColor) {
        view.backgroundColor = color
    }
}

在您的 Xib 中创建一种方法来传递委托并在所需的 buttonPress 上调用 didSelectColor 函数:

class ColorPickerXib {
    weak var delegate: ColorPickerProtocol?

    @IBAction func dismissButtonPressed(_ sender: UIButton) {
        delegate?.didSelectColor(color)
        self.dismiss()
    }
}

最后在 ViewController 中使用适当的委托实例化 Xib 并显示它:

let colorPicker = ColorPickerXib()
colorPicker.delegate = self
// Show Xib
于 2017-11-20T15:46:04.470 回答