ios - 选择自定义选择器 View 中的第一行时如何禁用按钮?

标签 ios swift uipickerview

我有一个在 2 个 View Controller 中使用的自定义 UIPickerView 类(也符合 UIPickerViewDelegate、UIPickerViewDataSource)。 所以在他们两个中我都有这个: myPickerView.delegate = myPickerViewdataSource相同。 所有行和组件都在该自定义选择器 View 类中配置。

我想在选择第一行时禁用我的 VC 中的按钮。 通常我会通过使用选择器 View 的委托(delegate)函数之一(pickerView(_:,didSelectRow:, inComponent:)来做到这一点,但是因为我使用了一个已经符合 UIPickerViewDelegate 的自定义函数,所以我不能不要那样做。

最佳答案

嗯,棘手。问题是选择器是它自己的委托(delegate),这使得解决方案有点复杂,但我可能会这样做:给选择器一个闭包,当所选行发生变化时调用该闭包。然后从委托(delegate)方法中调用该闭包。

class MyPickerView {
    typealias SelectedIndexClosure = (Int) -> Void
    var selectedIndexClosure: SelectedIndexClosure = { _ in }

...

    func picker(_ picker: UIPickerView, didSelectRow row: Int ...) {
        selectedIndexClosure(row)
    }
}

然后您将 selectedIndexClosure 设置为您希望在 View Controller 中运行的任何代码。

myPickerView.selectedIndexClosure = { [weak self] index in
    self?.button.enabled = (index == 1)
}

那应该就可以了。一个更惯用的解决方案可能是将选择器的数据源和委托(delegate)方法重构为 View Controller 拥有的新的、独立的对象,但这应该可以正常工作。

关于ios - 选择自定义选择器 View 中的第一行时如何禁用按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42775854/

相关文章:

iphone - 在选取器 View 中未选择第一个值

ios - 将多个渲染目标 (MRT) 与多重采样相结合在 iOS 设备上失败,而不是在模拟器上

ios - Xcode 单元测试构建失败,错误为 "Undefined symbols for architecture x86_64"

ios - UILabel 换行截尾

ios - 在同一行上使用两次“滑动删除”功能时应用程序崩溃

ios - 在 Facebook 上分享,手机上不显示文字。 ( swift )

ios - 用来自服务器的数据填充 UIPageViewController?

ios - 在 swift 中设置一个 Picker

ios - 我在哪里设置谷歌地图 API key 在 Action 扩展,iOS Swift

ios - 初始化UIButton并将其放置在具有UIPickerView的UIActionSheet中