2017-05-17 49 views
0

我已经在一个视图控制器中声明了一个协议,并且想要在其呈现视图控制器中调用一个函数。我不使用故事板。Swift协议委托在UIViewController中意外发现无

This delegate!.setWishListButton()导致错误unexpectedly found nil while unwrapping an optional。我知道我不应该使用!但它是为了测试,因为我的委托函数从来没有被调用过。

我知道有很多关于这方面的问题,但没有一个符合我的用法。我在UIView中有一个类似的模式,它工作正常。

这里是我的代码

protocol SetWishListButtonDelegate { 
    func setWishListButton() 
} 

class MyViewController: UIViewController { 

var delegate : SetWishListButtonDelegate? 

------ 

    func toggleWishListButton() { 

    delegate?.setWishListButton() 
} 

在另一个视图控制器

class anotherViewController: UIViewController, SetWishListButtonDelegate { 

let myViewController = MyViewController() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    myViewController.delegate = self 
} 

func setWishListButton() { 

    print("DELEGATE METHOD FIRED") 

    wishListButton.isSelected = true 
} 
+0

“someFunction”在哪里被调用? –

+0

已编辑的问题。调用函数调用API然后委托。 – markhorrocks

回答

0

这个工作之后,我删除的功能,我的视图控制器它是由按下按钮提交的第二个声明。