协议方法未调用

时间:2017-01-28 22:00:44

标签: ios swift

我正在尝试使用swift协议。我不知道它为什么不起作用。

第二个视图控制器:

protocol passBackTheVoice {
    func sendVoiceMessage(name: String)
}

class VoiceRecordViewController: UIViewController {
    var passBackDelegate: passBackTheVoice?
    ….
    ….

    func uploadCompleted() {
            self.passBackDelegate?.sendVoiceMessage(voiceName)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

First View Controller:

class ChatViewController: UIViewController, passBackTheVoice {
    var voiceRecordVC = VoiceRecordViewController()

    override func viewDidLoad() {
        voiceRecordVC.passBackDelegate=self
    }

    func sendVoiceMessage(name: String) {
        print("chat view \(name)")
    }
}

我的sendVoiceMessage方法没有调用。问题在哪里,我该如何解决?

Ps:不知道这是相关的,但是,首先我的ChatViewController显示然后用户触摸我正在向用户显示VoiceRecordViewController的按钮。然后用户创建一个语音文件,我想将此文件传回我的ChatViewController。

1 个答案:

答案 0 :(得分:1)

首先,如果您从segue展示视图控制器,则必须使用以下代码:

class ChatViewController: UIViewController, passBackTheVoice {


        override func viewDidLoad() {

        }

        func sendVoiceMessage(name: String) {
            print("chat view \(name)")
        }

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

            if segue.identifier == "YOUR_IDENTIFIER_IN_STORYBOARD" {
                let vc = segue.destination as! VoiceRecordViewController
                vc.delegate = self
            }

        }


    }

如果您手动使用此代码:

class ChatViewController: UIViewController, passBackTheVoice {

        override func viewDidLoad() {


        }

        func sendVoiceMessage(name: String) {
            print("chat view \(name)")
        }

        func goTovoiceRecordVC(){
            let voiceRecordVC = VoiceRecordViewController() // load from storyboard or nib whatever you want
            voiceRecordVC.passBackDelegate=self
            present(voiceRecordVC, animated: true, completion: nil)
        }

    }