将字符串选择从 UIPicker 转换为 UIColor 的最简单方法?

Easiest way to convert string selection from UIPicker into UIColor?

我正在练习委托,在我的练习项目中,我试图让用户 select 从选择器中选择他们最喜欢的颜色,然后在委托方法中使用该颜色(作为 UIColor)。

为清楚起见,这是我的简单协议:

protocol PersonDelegate {
    func makePerson(name: String, color: UIColor)
}

我有一组颜色供选择器使用:

let colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Cyan", "White", "Black"]

然后是一个空字符串变量,用于将用户的选择传递给:

var favoriteColor = ""

我的选择器方法是:

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return colors[row]
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return colors.count
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    favoriteColor = colors[row]
}

现在,当按下完成按钮时,将调用委托方法,我需要提供一个 UIColor。现在显然它不起作用,因为我试图在需要 UIColor:

时传入 String
@IBAction func doneButtonPressed(_ sender: Any) {

    let name = nameTextField.text
    let myColor = favoriteColor

    personDelegate.makePerson(name: name!, color: myColor)

    dismiss(animated: true, completion: nil)
}

我想知道如何将 String selection 从选择器转换为 UIColor,或者采用不同的方法来避免这种情况,然后再做一次方式。

编辑:到目前为止的完整代码

protocol PersonDelegate {
    func makePerson(name: String, color: UIColor)
}

class DelegateController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var colorPicker: UIPickerView!
var personDelegate: PersonDelegate!
let colors: [(string: String, color: UIColor)] = [("Red", .red), ("Orange", .orange), ("Yellow", .yellow), ("Green", .green), ("Blue", .blue), ("Cyan", .cyan)]
var favoriteColor: UIColor

override func viewDidLoad() {
    super.viewDidLoad()

}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return colors[row].string
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return colors.count
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    favoriteColor = colors[row].color
}

@IBAction func doneButtonPressed(_ sender: Any) {

    let name = nameTextField.text
    let myColor = favoriteColor

    personDelegate.makePerson(name: name!, color: myColor)

    dismiss(animated: true, completion: nil)
}

创建 [String : UIColor] 词典:

let dict = ["Red": UIColor.red, "Green": UIColor.green, ...]

然后用字符串查找颜色:

let color = dict[favoriteColor]!

或者您可以使 colors 数组对 StringUIColor:

let colors: [(string: String, color: UIColor)] = [("Red", .red), ("Green", .green)]

然后当你需要字符串时:

colors[row].string

当您需要颜色时:

colors[row].color