简体   繁体   English

以编程方式在视图控制器之间传递数据Swift

[英]passing data between view controllers programmatically Swift

I have two viewcontroller classes. 我有两个viewcontroller类。 MainViewController has a UITextField and SecondViewController has a UILabel. MainViewController具有UITextField,SecondViewController具有UILabel。 I want to print the text from the UITextField in the UILabe. 我想从UILabe中的UITextField打印文本。 Please tell me the best way to do this programmatically. 请告诉我以编程方式执行此操作的最佳方法。 Below is my code: 下面是我的代码:

// AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?


  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

window = UIWindow(frame: UIScreen.main.bounds) 窗口= UIWindow(框架:UIScreen.main.bounds)

window?.makeKeyAndVisible()

window?.rootViewController = MainViewController()

window?.backgroundColor = UIColor.yellow

application.statusBarStyle = .lightContent


return true
  }

 }

// MainViewController Class // MainViewController类

import UIKit

class MainViewController: UIViewController {


  let label = UILabel()

  let textField = UITextField()



  override func viewDidLoad() {

    super.viewDidLoad()


    view.backgroundColor = UIColor.gray
    setupLabel()
    setupTextField()
    setupButton()
  }

  func setupLabel() {

    label.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
    label.text = "welcome to my world"
    label.textColor = UIColor.yellow
    label.font = UIFont.boldSystemFont(ofSize: 25)
    label.textAlignment = .center
    label.layer.borderWidth = 2
    label.layer.borderColor = UIColor.yellow.cgColor
    label.layer.cornerRadius = 5
    view.addSubview(label)
  }

  func setupTextField() {

    textField.frame = CGRect(x: 10, y: 200, width: self.view.frame.size.width - 20, height: 60)
    textField.placeholder = "text here"
    textField.textAlignment = .center
    textField.font = UIFont.systemFont(ofSize: 25)
    textField.layer.borderWidth = 2
    textField.layer.borderColor = UIColor.yellow.cgColor
    textField.layer.cornerRadius = 5
    view.addSubview(textField)
  }

  func setupButton() {

    let button = UIButton()
    button.frame = CGRect(x: 50, y: 300, width: self.view.frame.size.width - 100, height: 60)
    button.setTitle("Enter", for: .normal)
    button.setTitleColor(UIColor.yellow, for: .normal)
    button.layer.borderWidth = 2
    button.layer.borderColor = UIColor.yellow.cgColor
    button.layer.cornerRadius = 5
    button.addTarget(self, action: #selector(buttonTarget), for: .touchUpInside)
    view.addSubview(button)
  }

  func buttonTarget() {

    // i missed here maybe
    }

}

// SecondViewController class // SecondViewController类

import UIKit

class SecondViewController: UIViewController {


    let secondLabel = UILabel()

  override func viewDidLoad() {

    super.viewDidLoad()

    setupLabelSecond()
  }


  func setupLabelSecond() {

    secondLabel.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
    secondLabel.text = "this is Second Page"
    secondLabel.textColor = UIColor.yellow
    secondLabel.font = UIFont.boldSystemFont(ofSize: 25)
    secondLabel.textAlignment = .center
    secondLabel.layer.borderWidth = 2
    secondLabel.layer.borderColor = UIColor.yellow.cgColor
    secondLabel.layer.cornerRadius = 5
    view.addSubview(secondLabel)
  }



}

you need to follow some steps 您需要遵循一些步骤

step1 第1步

initially embed with your initial VC to navigation controller , for eg 最初将您的初始VC嵌入到导航控制器中,例如

Now select the first controller in Storyboard and click on Editor > Embed in... > Navigation Controller. 现在,在情节提要中选择第一个控制器,然后单击“ 编辑器”>“嵌入...”>“导航控制器”。

在此处输入图片说明

step2 第2步

Now you have to link the second Controller in Storyboard with your new SecondViewController.swift file. 现在,您必须将故事板中的第二个Controller与新的SecondViewController.swift文件链接。

Select the yellow circle at the top of the controller, click on the Identify inspector panel icon on the right side of the XCode window, and type the name of your new .swift file in the Class and StoryboardID fields 选择控制器顶部的黄色圆圈,单击“ XCode”窗口右侧的“确定检查器”面板图标,然后在“类”和“ StoryboardID”字段中键入新的.swift文件的名称。

for eg 例如

在此处输入图片说明

step3 第三步

Passing a String 传递字符串

Now select the other controller in Storyboard and add this variable right below the SecondViewController class declaration: 现在,在Storyboard中选择另一个控制器,并在SecondViewController类声明的正下方添加此变量:

 class SecondViewController: UIViewController {


let secondLabel = UILabel()

  var stringPassed = ""

Make the app assign the value of this variable to secondLabel with the following line of code in the viewDidLoad() method 使用viewDidLoad()方法中的以下代码行,使应用将此变量的值分配给secondLabel

step4 第四步

on your first VC , inside the button 在您的第一个VC上,在按钮内

func buttonTarget() {

    let myVC = storyboard?.instantiateViewControllerWithIdentifier("SecondVC") as! SecondViewController
    myVC.stringPassed = label.text!

    navigationController?.pushViewController(myVC, animated: true)

}

finally you get the out put as 最终你得到了输出

 func setupLabelSecond() {

    secondLabel.frame = CGRect(x: 40, y: 80, width: 300, height: 60)

    if let outputText =  stringPassed
    {
    secondLabel.text = outputText
    }else
     {
      secondLabel.text = "this is Second Page"
     }
    secondLabel.textColor = UIColor.yellow
    secondLabel.font = UIFont.boldSystemFont(ofSize: 25)
    secondLabel.textAlignment = .center
    secondLabel.layer.borderWidth = 2
    secondLabel.layer.borderColor = UIColor.yellow.cgColor
    secondLabel.layer.cornerRadius = 5
    view.addSubview(secondLabel)
  }

for sample you can get the tutorial here 对于示例,您可以在这里获得教程

update for XIB XIB更新

   func buttonTarget() {

    var vcPass = SecondViewController(nibName: "SecondViewController", bundle: nil)
     vcPass.stringPassed = label.text!
    self.navigationController?.pushViewController(vcPass, animated: true)


}

update for without XIB and Storboard 没有XIB和Storboard的更新

change your appdelegate 更改您的appdelegate

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)
    // Override point for customization after application launch.

    let navigation = UINavigationController(rootViewController: MainViewController())
    self.window?.rootViewController = navigation
    self.window?.makeKeyAndVisible()
    return true
 }

on your MainViewController 在您的MainViewController上

 func buttonTarget() {

     var vcPass = SecondViewController()
     vcPass.stringPassed = label.text!
    self.navigationController?.pushViewController(vcPass, animated: true)

 }

Passing a String 传递字符串

Now select the other controller in Storyboard and add this variable right below the SecondViewController class declaration: 现在,在Storyboard中选择另一个控制器,并在SecondViewController类声明的正下方添加此变量:

 class SecondViewController: UIViewController {


let secondLabel = UILabel()

  var stringPassed = ""

Make the app assign the value of this variable to secondLabel with the following line of code in the viewDidLoad() method 使用viewDidLoad()方法中的以下代码行,使应用将此变量的值分配给secondLabel

func setupLabelSecond() { func setupLabelSecond(){

    secondLabel.frame = CGRect(x: 40, y: 80, width: 300, height: 60)

    if let outputText =  stringPassed
    {
    secondLabel.text = outputText
    }else
     {
      secondLabel.text = "this is Second Page"
     }
    secondLabel.textColor = UIColor.yellow
    secondLabel.font = UIFont.boldSystemFont(ofSize: 25)
    secondLabel.textAlignment = .center
    secondLabel.layer.borderWidth = 2
    secondLabel.layer.borderColor = UIColor.yellow.cgColor
    secondLabel.layer.cornerRadius = 5
    view.addSubview(secondLabel)
  }

I know 2 possible ways. 我知道2种可能的方式。

1) Embed your initial view controller in navigation controller. 1)将您的初始视图控制器嵌入导航控制器中。 In your 2nd view create a var. 在第二个视图中,创建一个变量。 eg 例如

var x = ""

in your 1st view create a text field outlet and object of second view controller , 在您的第一个视图中,创建一个文本字段出口和第二个视图控制器的对象,

@IBOutlet weak var enteredName: UITextField!

let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController

then, assign the entered text field through that object to variable x. 然后,通过该对象将输入的文本字段分配给变量x。

secondVC.x = enteredName.text!

in your second vc you can assign the value of x to your label. 在第二个vc中,您可以将x的值分配给标签。

mylabel.text = x

____________________________________________________________________ ____________________________________________________________________

Second Method is using user Defaults. 第二种方法是使用用户默认值。

take user input and set that as user default. 接受用户输入并将其设置为用户默认值。

 let defaults = UserDefaults.standard   
defaults.set(self.enteredName.text!,forKey: "userName")
    defaults.synchronize()

and in your second view use 在第二个视图中使用

let defaults = UserDefaults.standard  
yourlabel.text = defaults.object(forKey: "userName")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM