首页 > 解决方案 > 如何使用 UIColorPickerViewController 更改两件事的颜色

问题描述

我想用 UIColorPickerViewController 改变两种颜色(图标和背景)。

现在我可以更改图标的颜色。但我也需要改变背景的颜色。

但是,我不知道如何分离扩展部分。

目前,我的代码如下;

@IBAction func btnColorPickerPressed(_ sender: Any) {
    let colorPickerVC = UIColorPickerViewController()
    colorPickerVC.delegate = self
    present(colorPickerVC, animated: true) {
    }
}

@IBAction func bgColorPickerPressed(_ sender: Any) {
    let colorPickerVC = UIColorPickerViewController()
    colorPickerVC.delegate = self
    present(colorPickerVC, animated: true) {
    }
}
extension ViewController : UIColorPickerViewControllerDelegate {
func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) {
    showImage()
    
}

func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
    iconColor = viewController.selectedColor

}

}

标签: swift

解决方案


创建 2 个不同的UIColorPickerVieweController并简单地检查哪个是哪个

@IBAction func btnColorPickerPressed(_ sender: Any) {
    let colorPickerVC = UIColorPickerViewController()
    colorPickerVC.delegate = self
    colorPickerVC.view.tag = 1
    present(colorPickerVC, animated: true) {
    }
}

@IBAction func bgColorPickerPressed(_ sender: Any) {
    let colorPickerVC = UIColorPickerViewController()
    colorPickerVC.delegate = self
    colorPickerVC.view.tag = 2
    present(colorPickerVC, animated: true) {
    }
}

func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
    if(viewController.view.tag == 1) {
        iconColor = viewController.selectedColor
    }
    else if(viewController.view.tag == 2) {
        backgroundColor = viewController.selectedColor
    }

}

推荐阅读