更新时间:2022-06-06 22:26:11
您需要在模型中添加一个额外的数据作为选定值,然后在选择选择器视图时将该值设置为文本字段
you need to add a extra data into model as selected value then set that value to textfield when selecting picker view
class QuestionCollectionViewController: UICollectionViewController,UITextFieldDelegate {
// Mark: - Properties
let reuseIdentifier = "QuestionCell"
let survey: Survey? = UserDefaults.getCodable(.survey)
// number of cells is based on the
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return survey?.questions.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as! QuestionViewCell
let data = survey?.questions[indexPath.item]
cell.questionResponse.delegate = self
cell.questionResponse.tag = indexPath.item
cell.questionResponse.text = data.selectedValue
return cell
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let index = IndexPath(item: textField.tag, section: 0)
constructQuestionViewCell(cell,withQuestion:survey?.questions[index.item])
}
private func constructQuestionViewCell(_ cell: QuestionViewCell, withQuestion question: SurveyQuestion? = nil) {
cell.questionTitle.text = question?.title
cell.questionTitle.numberOfLines = 0
cell.questionTitle.sizeToFit()
cell.questionResponse.frame.origin.y = cell.questionTitle.frame.maxY + 7
cell.questionResponse.inputAccessoryView = doneToolbar()
cell.questionResponse.layer.borderColor = UIColor.lightGray.cgColor
cell.questionResponse.layer.borderWidth = 1.0
cell.questionResponse.layer.cornerRadius = 5.0
// TODO refactor and remove else if keying off of "ratepain" once survey questions have been updated in the api
if (question?.type == "number_list") {
let options = question?.values ?? [" ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
let picker = CustomPickerView(frame: .zero, textView: cell.questionResponse, options: options)
//cell.questionResponse.inputView = picker
question?.selectedValue = picker.value
picker.reloadAllComponents()
}
else if (question?.key == "ratepain") {
let options = [" ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
let picker = CustomPickerView(frame: .zero, textView: cell.questionResponse, options: options)
//cell.questionResponse.inputView = picker
question?.selectedValue = picker.value
}
cell.sizeToFit()
}