通过闭包传递UIPickerView行索引

时间:2017-11-27 08:11:56

标签: ios swift closures

我的目标是将rowClosure传递给另一个视图控制器,但我只是坚持到这里。我应该做些什么来解决它?

ViewController1

var rowClosure : (Int) -> (Int) = { x in return x}

  func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    self.rowClosure(row)

    }

ViewController2

let vc1 = ViewController1()
    var row: Int!
row = vc1.rowClosure

但是,它不起作用

1 个答案:

答案 0 :(得分:0)

如果你想使用闭包,你的代码看起来应该是这样的:

VC1

var rowClosure : ((Int) -> Void)?

  func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    self.rowClosure?(row)

    }

然后在VC2中,您获得对VC1的引用,并设置一个闭包,当您从VC1调用闭包时,需要在VC2中执行代码:

vc1.rowClosure = { (vc1Row) in
    //do something with row, for example
    vc2.row = vc1Row
}