如何在选择自定义选取器视图中的第一行时禁用按钮?

时间:2017-03-14 00:30:50

标签: ios swift uipickerview

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

我想在选择第一行时禁用我的VC中的按钮。 通常我会使用其中一个选择器视图的委托函数(pickerView(_:,didSelectRow:, inComponent:)来完成此操作,但由于我使用的是一个已经符合UIPickerViewDelegate的自定义函数,我无法做到这一点。

2 个答案:

答案 0 :(得分:1)

嗯,狡猾。问题是选择器是它自己的委托,这使得解决方案有点复杂,但这就是我可能做的事情:给选择器一个闭包,当所选行改变时调用它。然后从委托方法中调用该闭包。

const images = [
  { url: 'www.foo.com', uploadUrl: '/foo', name: 'foo' }
, { url: 'www.bar.com', uploadUrl: '/bar', name: 'bar' }
, { url: 'www.baz.com', uploadUrl: '/baz', name: 'baz' }
]

const promiseTimeout = (delay, promise) => 
  Promise.race([
    new Promise((resolve, reject) => 
      setTimeout(resolve, delay, {
        status: 'error',
        msg: 'took too long!'
      })
    ),
    promise
  ])

const downloadPhoto = ({ url, uploadUrl, name }) => 
  promiseTimeout(
    1000,
    new Promise((resolve, reject) => {
      setTimeout(resolve, 3000, {
        status: 'success',
        msg: `this will never resolve ${url}`
      })
    })
  )

// map images array [...image] into [...Promise(image)]
const imagePromises = images.map(downloadPhoto)
// resolve all promises
Promise.all(imagePromises)
// called once all promises are resolved with array of results
.then(images => {
  // map over the resolved images and do further processing
  images.map(console.log.bind(console, 'Image resolved'))
})
// promises no longer reject, you will need to look at the status
.catch(console.log.bind(console, 'Error: '))

然后,您将class MyPickerView { typealias SelectedIndexClosure = (Int) -> Void var selectedIndexClosure: SelectedIndexClosure = { _ in } ... func picker(_ picker: UIPickerView, didSelectRow row: Int ...) { selectedIndexClosure(row) } } 设置为您希望在视图控制器中运行的任何代码。

selectedIndexClosure

那应该这样做。更惯用的解决方案可能是重构选择器的数据源并将方法委托给视图控制器拥有的新的独立对象,但这应该可以正常工作。

答案 1 :(得分:0)

如果您只需要设置一次,就可以说self.button.isEnabled = self.picker.selectedRow(inComponent: 0) == 0。如果您需要在移动选择器后重新启用它,或者如果您移回第一行则禁用它,则需要使用相同的委托方法。