我有一个在 2 个 View Controller 中使用的自定义 UIPickerView 类(也符合 UIPickerViewDelegate、UIPickerViewDataSource)。
所以在他们两个中我都有这个:
myPickerView.delegate = myPickerView
与dataSource
相同。
所有行和组件都在该自定义选择器 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/