簡體   English   中英

迅速在視圖控制器之間委托實現

[英]Delegate implementation in between viewcontrollers in swift

我有2個視圖控制器VCAVCB VCA轉移到VCB並獲得一定價值,效果很好

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

但反過來,我想調用的方法VCAVCB上載的某些數據后VCB 然后刷新VCA文本字段值。 我本可以在VCA中顯示刷新的代碼,但由於某些原因,我不打算這樣做,而是嘗試實現委托。 我寫了一些代碼為:

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
}
}

提前致謝

在VCA的viewDidLoad ,您已經創建了mobileVC但是當您過渡到VCB時,正在創建一個名為vc的VCB新實例。 mobileVC使用。 您有幾種選擇:

在創建vcmobileVC設置為類屬性或設置委托。

后者為:

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

我不知道您的情況是什么,但是最簡單的解決方案是將委托方法移到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

是的, Delegate是您獲得重視的方式。 快速完全實現委托存在一些問題。 在這里,我提供了可以完全指導您如何快速實現委托的鏈接。

委托Swift

就像您說的那樣,App在調用委托時崩潰。 這意味着,您的方法在VCA不可用,或者委托沒有VCA引用。 請檢查這兩個條件。

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM