在容器视图(带有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/