Swift 3.0委托协议不起作用

时间:2017-08-22 10:28:56

标签: ios swift delegates protocols

我在两个视图控制器中创建了委托协议。但委托方法不会调用我的代码片段。这是什么原因。我无法找到问题,请发表您的建议以重温此问题。

主视图控制器

class ViewController: UIViewController, testDelegateMethod {

override func viewDidLoad() {
    super.viewDidLoad()

    let vw = testViewController()
    vw.delegateTest = self

    let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController")
    self.navigationController?.pushViewController(push!, animated: true)
}

func testMethod(value:String) {
    print("Hai", value)
}
}

子视图控制器

protocol testDelegateMethod {
func testMethod(value:String)
}

class testViewController: UIViewController {
var delegateTest : testDelegateMethod?

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func actSubmit(_ sender: Any) {
    delegateTest?.testMethod(value: "Hello how are you!")
}

}

5 个答案:

答案 0 :(得分:3)

由于这一行而面临的问题

let vw = testViewController()
    vw.delegateTest = self

您已创建testViewController vw 的实例,以及vw实例的已分配代理

在下一行

let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController")
self.navigationController?.pushViewController(push!, animated: true)

您正在创建testviewcontroller的不同实例推送

不需要此代码,

let vw = testViewController()
        vw.delegateTest = self

取而代之的是

let push testViewController = self.storyboard.instantiateViewController(withIdentifier: "testViewController") as! testViewController
push.delegateTest = self
self.navigationController?.pushViewController(push, animated: true)

答案 1 :(得分:2)

viewdidLoad()方法

中更新这些更改
override func viewDidLoad() {
    super.viewDidLoad()

   if let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") as? SelectionScreen
  {
    push.delegateTest = self
  }

}

答案 2 :(得分:2)

let vw = testViewController() // Your are doing wrong code 
vw.delegateTest = self   

仅使用此

我希望它对你有用

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let push = storyboard.instantiateViewController(withIdentifier:"testViewController")as! testViewController
push.delegateTest = self
self.navigationController?.pushViewController(push, animated: true)

答案 3 :(得分:2)

此代码段没有意义。您只需创建一个对象,但不会进一步使用它。请删除此代码段。

  let vw = testViewController()
        vw.delegateTest = self

这样做:

override func viewDidLoad() {
    super.viewDidLoad()
    let pushVC = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") as! testViewController
 pushVC.delegateTest = self

    self.navigationController?.pushViewController(pushVC, animated: true)
}

答案 4 :(得分:2)

我想,你把代码func testMethod(value:String) { print("Hai", value) } 进入viewDidLoad及以上let push = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") self.navigationController?.pushViewController(push!, animated: true)