我创建了一个可重用的控件,用于我正在处理的项目中。它只是 aUITextField
将 a 显示UIPickerView
为它的inputView
。
class InputPickerView: UIView {
@IBOutlet private var view: UIView!
@IBOutlet weak private var titleLabel: UILabel!
@IBOutlet weak private var textField: UITextField!
private(set) var pickerView = UIPickerView()
var options: [String] = []
var option: String {
get {
return textField.text ?? ""
}
set {
textField.text = newValue
}
}
var title: String = "" {
didSet {
titleLabel.text = title
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("InputPickerView", owner: self, options: nil)
addSubview(view)
view.frame = bounds
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
pickerView.dataSource = self
pickerView.delegate = self
textField.inputView = pickerView
}
}
extension InputPickerView: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return false
}
}
extension InputPickerView: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return options.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return options[row]
}
}
extension InputPickerView: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
textField.text = options[row]
}
}
目前它只接受一个字符串数组并返回一个字符串。我试图通过在泛型的帮助下使其接受/返回任何类型(例如结构和枚举)来使其更具可重用性。我希望使结构/枚举符合CustomStringConvertible
并使用描述属性值作为选择器视图选项的显示值。
但我很难弄清楚如何做到这一点。我遇到的所有文章、问题、教程都涉及协议。所以我有点困惑。
如何使options
andoption
变量接受/返回具有泛型的任何类型?
我的意思是,假设我创建了一个名为State
.
struct State {
let id: Int
let title: String
}
extension State: CustomStringConvertible {
var description: String {
return title
}
}
我没有将字符串传递给视图,而是试图让它接受属性中的State
对象实例,options
并让视图使用该description
值作为显示值。当用户选择一个时,它会通过属性返回选择的State
对象。option