将容器视图中没有Segue的数据传递到MainVC

时间:2018-01-13 12:45:29

标签: ios swift containers segue viewcontroller

想法在按下Container View(使用ViewController)中的按钮到Main ViewController之后发送值trackNumber到recivedTrackNumber而没有segue,因为它们在同一个视图中。如何通知主视图控制器(recivedTrackNumber)有关trackNumber的值?

容器视图(使用ViewController)看起来像按钮

 import UIKit
 class SelectSoundVC: UIViewController {

   var trackNumber: Int!

   @IBAction func winterSoundBut(_ sender: UIButton) {
    trackNumber = 1

  } 

}

和主ViewController

class MainVC: UIViewController {

   var recivedTrackNumber: Int!

}

Main.storyboard Screenshot

3 个答案:

答案 0 :(得分:2)

Delegate模式可以帮到你。首先,您需要委托协议:

protocol SelectSoundVCDelegate {
    func didSelectTrackNumber(_ trackNumber: Int)
}

使用接受trackNumber值的func。接下来,您需要在delegate中创建SelectSoundVC属性:

class SelectSoundVC: UIViewController {

    weak var delegate: SelectSoundVCDelegate?
    var trackNumber: Int!

    @IBAction func winterSoundBut(_ sender: UIButton) {
        trackNumber = 1
        delegate?.didSelectTrackNumber(trackNumber)
    } 

}  

将调用didSelectTrackNumber中的@IBAction。请注意,delegate属性应该很弱,以避免引用周期。最后一步,在MainVC中,您应设置delegate的{​​{1}}属性:

SelectSoundVC

这部分有点棘手,因为您需要selectSoundVC.delegate = self 的实例来设置委托。您可以使用SelectSoundVC方法进行设置,例如:

prepareFoSegue

答案 1 :(得分:0)

第三种方法;-)
如果您从代码(来自MainVC)实例化第二个视图控制器,那么您可以轻松访问该变量:

let selectSoundVC = SelectSoundVC()
recivedTrackNumber = selectSoundVC.trackNumber
present(selectSoundVC, animated: true, completion: nil)

这应该有效!

答案 2 :(得分:-1)

您可以使用prepareForSegue(_ :)在初始化时检索对嵌入式视图控制器的强引用。只需将您的segue标识符设置为" EmbedSegue"在故事板中

// MainVC
private var embeddedViewController: SelectSoundVC?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? SelectSoundVC,
        segue.identifier == "EmbedSegue" {
        self.embeddedViewController = vc
    }
}

同时将曲目属性更改为可选,因为无法选择曲目。

// SelectSoundVC
var trackNumber: Int?

然后,您可以从MainVC的任何位置检索您的曲目编号:

// Here you can access to the trackNumber property, no need to duplicate its value (Single Responsability)
if let embeddedViewController = self.embeddedViewController, let trackNumber = embeddedViewController.trackNumber {
    print("Track Number \(trackNumber)")
}