You need to enable JavaScript to run this app. UIPickerView点击Done按钮总是选中最后一项的问题如何解决
优惠活动
大模型
产品
解决方案
定价
更多

UIPickerView点击Done按钮总是选中最后一项的问题如何解决

UIPickerView点击Done自动滚动到最后一项排查方案

常见原因及对应修复方法

  • 数据源行数不一致
    检查numberOfRowsInComponent数据源方法的返回值,必须严格等于filterComponent.count,不能硬编码固定数值。如果filterComponent数组会动态更新,每次更新后必须调用filterPickerView.reloadAllComponents()刷新picker的缓存,避免picker保存的行数和实际数据源行数不匹配导致乱跳。
  • 弹出picker时未同步当前选中项
    你当前的textFieldDidBeginEditing方法只设置了inputView,没有把picker的选中行和输入框已有的文本对齐,picker默认会选中第0行,当内部状态校验不匹配时就会出现自动滚动的问题,修改该方法如下:
    func textFieldDidBeginEditing(_ textField: UITextField) {
        guard textField == filterPropertyPicker else {
            return
        }
        textField.inputView = filterPickerView
        // 新增:同步picker选中行和当前输入框值
        let currentSelectedRow = filterComponent.firstIndex(of: textField.text ?? "") ?? 0
        filterPickerView.selectRow(currentSelectedRow, inComponent: 0, animated: false)
    }
    
  • Done按钮点击逻辑异常
    检查你绑定的Done按钮点击回调方法,确保只执行输入框收键盘操作,不要额外调用picker的selectRow、reload等方法,示例正确写法:
    @objc func doneButtonTapped() {
        filterPropertyPicker.resignFirstResponder()
    }
    
  • 额外校验:避免didSelectRow的异常触发
    可以在pickerView(_:didSelectRow:inComponent:)方法中加一层判断,只有当picker是当前第一响应者对应的inputView时才执行逻辑,避免非主动操作触发的回调干扰:
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        guard filterPropertyPicker.isFirstResponder, row < filterComponent.count && row >= 0 else {
            return
        }
        viewModel.filterResults(selectedIndex: filterPropertySegments.selectedSegmentIndex, selectedRow: row)
        filterPropertyPicker.text = filterComponent[row]
    }
    

内容的提问来源于stack exchange,提问作者Umar Maikano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 19:36:04