我正在练习委托,在我的练习项目中,我试图让用户从选择器中选择他们喜欢的颜色,然后在委托方法中使用该颜色(作为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。目前,它显然不起作用,因为我在需要String
时尝试传递UIColor
:
@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
,或者可能采取另一种方法来使不必要的选择和另一种方式实现。
编辑:到目前为止的完整代码
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)
}
答案 0 :(得分:1)
创建[String : UIColor]
字典:
let dict = ["Red": UIColor.red, "Green": UIColor.green, ...]
然后只用字符串查找颜色:
let color = dict[favoriteColor]!
或者您可以将colors
和String
的{{1}}数组配对:
UIColor
然后在需要字符串时:
let colors: [(string: String, color: UIColor)] = [("Red", .red), ("Green", .green)]
以及当您需要颜色时:
colors[row].string