ios - 如何从模态 XIB 设置 VC 的背景颜色

标签 ios swift xib uibackgroundcolor

在此应用程序中,我希望允许用户更改主菜单的背景颜色。 在 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/

相关文章:

iphone - iOS:XIB 中使用的图像名称

iOS 动画——像 Siri 一样向上滚动文本

ios - 如何在 FSCalendar 中禁用标题占位符(上个月/下个月的日期)

swift - 授予 OSX 沙盒查找器同步扩展持久写入访问权限

swift - 我想按日期在 firebase 中保存数据意味着用户保存的所有数据都保存在该日期

ios - UICollectionView 在某些单元格上重复标签和图像

ios - 子类化自定义 UIViewController(使用 xib)以添加其他行为

ios - 在 Storyboard 中调用 xib

objective-c - 检测特定 View 是否是 WebView

javascript - DIV 在内容改变之前跳到顶部