如何将数据从弹出视图控制器发送到主视图控制器.传递字符串,以便我可以将其作为主视图中的标签文本做



我尝试了许多方法,将数据从我的弹出视图控制器发送到主视图控制器。但是失败了。任何人都可以帮助我吗?我正在使用"作为弹出式" segue。我想在弹出视图的Textfield中输入的文本作为主视图的标签文本。

从弹出视图中,数据使用Swift 3中的协议发送到Main ViewController。在此处输入图像描述完整的详细信息如下...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
}
}
  1. 弹出视图控制器,带有协议,命名为senddatatoviewprotocol。3. Protocol在popupviewController之外声明。
  2. 不要忘记将ViewController分配到PopupViewController。
  3. 在ViewController WistIdentifier中:" PopupViewController"," PopupViewController"是PopupViewController Storyborad ID。
  4. 请参阅附件。

     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()
     }
    }
    

首先,将临时变量保留在主viewController中。让我们称之为:
var somethingCool: String?

然后,在您的弹出视图controller代码中,假设您在那里触发了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"
        }
    }
}

相关内容

最新更新