运行func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
UIPickerView.selectRow(4, inComponent: 0, animated: false)
方法
或者存档的正确方法是什么?
我的实施
let pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
pickerView.selectRow(0, inComponent: 0, animated: false)
textField.inputView = pickerView
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
答案 0 :(得分:7)
这是选择行
self.yourPickerViewName.selectRow(2, inComponent: 0, animated: true)
这将触发方法
self.pickerView(self.yourPickerViewName, didSelectRow: 2, inComponent: 0)
将它们组合起来模拟用户操作
答案 1 :(得分:2)
当您以编程方式选择行时,绝对不会发现@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
private messagesService: MessagesService
private router: Router
constructor(
private injector: Injector, // DI workaround (https://stackoverflow.com/a/41585902)
private errorLoggerService: ErrorLoggerService
) {
// DI workaround (https://stackoverflow.com/a/41585902)
setTimeout(() => (this.messagesService = injector.get(MessagesService)))
setTimeout(() => (this.router = injector.get(Router)))
}
handleError(error) {
if (error instanceof HttpErrorResponse) {
this.handleServerError(error)
} else if (error instanceof ClientError) {
this.handleClientError(error)
} else {
this.handleUnexpectedError(error)
}
}
未被调用的错误。文档说:
当用户选择组件中的行时,由选取器视图调用。
它是一种仅在用户选择行时才会调用的委托方法。所以如果你选择这样一行,它自然不会被调用:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
您接受的答案中的黑客行为有效,但从视图控制器调用委托方法并不是一个好习惯。我建议您创建另一种方法,当用户或编程选择行时,它将执行您想要的操作:
e.g。
pickerView.selectRow(0, inComponent: 0, animated: false)
然后在你的委托方法中:
func doStuff(for row: Int, component: Int) {
// Do your stuff here
}
并以编程方式选择行:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
doStuff(for: row, component: component)
}
如果您需要使用pickerView.selectRow(0, inComponent: 0, animated: false)
doStuff(for: 0, component: 0)
方法中的pickerView执行某些操作,则可以添加另一个参数并在调用时将其传递,或直接访问pickerView变量。