在此应用程序中,我希望允许用户更改主菜单的背景颜色。 在 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
用户然后点击“确认”按钮,这将关闭 View 并返回到 MenuVC:
@IBAction func confirmBtnPressed(_ sender: Any) {
dismiss(animated: false, completion: nil)
}
这就是我正在努力解决的问题: 在“ConfirmBtnPressed”操作期间,我希望 MenuVC 背景颜色也更改为 ColorPickerVC 背景颜色(用户之前选择的颜色)
关于如何实现这一目标有什么想法吗?
谢谢, 斯科特
最佳答案
您应该了解委托(delegate)模式:
首先创建一个定义所需功能的协议(protocol):
protocol ColorPickerProtocol: class {
func didSelectColor(_ color: UIColor)
}
使用该协议(protocol)扩展您的 ViewController 并实现该方法:
class BackgroundColorViewController: UIViewController, ColorPickerProtocol {
func didSelectColor(_ color: UIColor) {
view.backgroundColor = color
}
}
在 Xib 内部创建一种方法来传递委托(delegate)并在所需的按钮按下时调用 didSelectColor 函数:
class ColorPickerXib {
weak var delegate: ColorPickerProtocol?
@IBAction func dismissButtonPressed(_ sender: UIButton) {
delegate?.didSelectColor(color)
self.dismiss()
}
}
最后在 ViewController 中使用适当的委托(delegate)实例化 Xib 并显示它:
let colorPicker = ColorPickerXib()
colorPicker.delegate = self
// Show Xib
关于ios - 如何从模态 XIB 设置 VC 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47395428/