我尝试了很多方法将数据从弹出视图控制器发送到主视图控制器。但失败了。任何人都可以帮助我。 我正在使用“礼物作为popover”segue。我希望在弹出视图的文本字段中输入的文本作为主视图的标签文本。
答案 0 :(得分:3)
从弹出视图,数据使用Swift 3中的协议发送到主ViewController。 enter image description here 完整的详细信息如下...... 1.使用名为sendDataToViewProtocol的协议查看控制器实现。
import UIKit
class ViewController: UIViewController,sendDataToViewProtocol {
@IBOutlet weak var lshowDataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnShowPopUpDialog(_ sender: Any) {
let popUpVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PopupVIewController") as! PopupVIewController
//Don't forget initialize protocal deletage
popUpVc.delegate = self
self.addChildViewController(popUpVc)
popUpVc.view.frame = self.view.frame
self.view.addSubview(popUpVc.view)
popUpVc.didMove(toParentViewController: self)
}
func inputData(data: String) {
lshowDataLabel.text = data
}
}
请参阅附图。
import UIKit
protocol sendDataToViewProtocol {
func inputData(data:String)
}
class PopupVIewController: UIViewController {
//Protocol object
var delegate:sendDataToViewProtocol? = nil
@IBOutlet weak var txtInputFieldText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor
.black.withAlphaComponent(0.8)
}
@IBAction func btnSendDataToViewController(_ sender: Any) {
//"Check Delegate nil"
if(delegate != nil){
//Check textField is empty
if(txtInputFieldText.text != ""){
//set textField Data to protocol Function
delegate?.inputData(data: txtInputFieldText.text!)
self.view.removeFromSuperview()
}
}
}
@IBAction func btnClose(_ sender: Any) {
self.view.removeFromSuperview()
}
}
答案 1 :(得分:0)
首先,在Main ViewController中保留一个临时变量。我们称之为:
var somethingCool: String?
然后,在弹出的ViewController代码中,假设您有segue触发器,则需要添加一个新方法。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "your_segue_identifier" {
if let vc = segue.destination as? MainViewController {
vc.somethingCool = "whatever_you_want"
}
}
}