在swift中的viewcontrollers之间委托实现

时间:2016-01-22 04:10:56

标签: ios swift delegates

我有2个视图控制器VCAVCB。 从某个值VCA移动到VCB,工作正常

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("VCB") as! VCB
vc.entity = somevalue
self.navigationController?.pushViewController(vc, animated: true)

但反过来说,我想在从VCA上传某些数据后,从VCB调用VCB中的方法。然后刷新文本字段值VCA。我可以在VCA中的viewwillappear中重新刷新代码,但由于某种原因我不会这样做但是试图实现委托。 我写了一些代码:

VCA:

class ProfileEditViewController:UIViewControoler, MobileVerifyDelegate{
override func viewDidLoad() {

    super.viewDidLoad()
    let mobileVC = MobileVerificationViewController()
    mobileVC.delegate = self
}

//MARK: - Mobileverify Delegate method
func delegateMethod() {
    print("a")

}
}

VCB:

    protocol MobileVerifyDelegate{
    func delegateMethod()
}


class MobileVerificationViewController: UIViewController{
 var delegate: MobileVerifyDelegate! = nil
func certainFunction(){
     //aftersuccessful upload
     self?.delegate.delegateMethod()// code crashes
}
}

提前致谢

3 个答案:

答案 0 :(得分:0)

viewDidLoad的VCA中,您创建了mobileVC但是当您转换到VCB时,您正在创建一个名为vc的VCB新实例。 mobileVC未按原样使用。您有几个选择:

使mobileVC成为一个类属性,或在创建vc时设置委托。

后者将是:

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("VCB") as! VCB
vc.entity = someValue
vc.delegate = self
self.navigationController?.pushViewController(vc, animated: true)

在旁注中,让您的代表确认课程协议,以便您可以将代表设置为弱。

protocol MobileVerifyDelegate: class {
    func delegateMethod()
}

class MobileVerificationViewController: UIViewController {
    weak var delegate: MobileVerifyDelegate?

    func certainFunction() {

        // After successful upload
        delegate?.delegateMethod()
    }
}

请注意,当您设置隐式展开的属性时,它已经是nil。因此,再次将其设置为nil是多余的。

var delegate: MobileVerifyDelegate! = nil // "= nil" is not needed

答案 1 :(得分:0)

我不知道您的情况如何,但最简单的解决方案是移动委托方法并委托给VCB。如果出于某种原因,您VCA必须是委托类,那么您需要创建它的实例或将其传递给VCB

//Set delegate when you push to the new controller in VCA
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("VCB") as! VCB
vc.entity = somevalue
vc.delegate = self //Sets VCA as VCB's Delegate        
self.navigationController?.pushViewController(vc, animated: true)

//Inside VCB
self.delegateMethod() //Now you can call any delegate protocol methods from VCA

答案 2 :(得分:0)

Ya,Delegate是您获得所需内容的方式。在swift中完全实现委托有一些问题。在这里,我提供链接,完全指导您如何在swift中实现委托。

Delegate In Swift

正如你所说,App在调用委托时崩溃了。这意味着,VCA中的方法不可用,或者委托未引用VCA。请检查这两个条件。

由于

相关问题