在容器视图(带有ViewController)中按下按钮后,将值trackNumber发送到主ViewController以接收不带segue的trackNumber,因为它们在同一视图中。如何通知主视图控制器(recivedTrackNumber)trackNumber的值?
容器视图(带有ViewController)与按钮类似

 import UIKit
 class SelectSoundVC: UIViewController {

   var trackNumber: Int!

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

  }

}

和主视图控制器
class MainVC: UIViewController {

   var recivedTrackNumber: Int!

}

Main.storyboard Screenshot

最佳答案

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的属性:
selectSoundVC.delegate = self

这部分有点棘手,因为您需要SelectSoundVC的实例来设置委托。您可以在SelectSoundVC方法中设置它,例如:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let viewController = segue.destination as? SelectSoundVC, segue.identifier == "SelectSoundVC" {
        viewController.delegate = self
    }
}

关于ios - 将没有Segue的数据从Container View传递到MainVC,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48239992/

10-16 17:13