ViewController将结果返回给调用它的ViewController

时间:2018-06-01 13:03:08

标签: ios xcode uiviewcontroller

我想从 ViewController-A

打开新的 ViewController-B

然后在关闭 ViewController-B 之后,它会将某些值(结果)返回到 ViewController-A

是否可以不使用通知?

如果是,那么如何?

1 个答案:

答案 0 :(得分:0)

更多"清洁"这样做的方法是使用委托模式。 实现此模式的步骤:

  1. 在ViewController-B中声明协议,例如:

     protocol ViewControllerAUpdatingProtocol: class {
    
         func update(withSomeValue someValue: SomeValueType)
    
     }
    

    将它设为class-only,因为我们知道ViewController-A类对象将符合它。

  2. 添加"委托" ViewController-B的属性:

    weak var delegate: ViewControllerAUpdatingProtocol!
    

    如果不一定要更新ViewController-A,您可以将此属性设为可选:

    weak var delegate: ViewControllerAUpdatingProtocol?
    
  3. 现在拨打"更新"您关闭ViewController-B的地方的委托方法。

    delegate.update(withSomeValue: yourValue)
    
  4. 然后将ViewController-A符合协议ViewControllerAUpdatingProtocol:

    extension ViewControllerA: ViewControllerAUpdatingProtocol {
         func update(withSomeValue someValue: SomeValueType) {
              // your implementation goes here
         }
     }
    
  5. 初始化"委托" ViewController-B的属性 的ViewController-A:

        viewControllerBInstance.delegate = self