想法在按下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!
}
答案 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)")
}