passing data between view controllers programmatic

2019-09-17 11:26发布

I have two viewcontroller classes. MainViewController has a UITextField and SecondViewController has a UILabel. I want to print the text from the UITextField in the UILabe. 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)

window?.makeKeyAndVisible()

window?.rootViewController = MainViewController()

window?.backgroundColor = UIColor.yellow

application.statusBarStyle = .lightContent


return true
  }

 }

// MainViewController Class

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

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



}

标签: ios swift swift3
2条回答
仙女界的扛把子
2楼-- · 2019-09-17 11:51

I know 2 possible ways.

1) Embed your initial view controller in navigation controller. 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.

secondVC.x = enteredName.text!

in your second vc you can assign the value of x to your label.

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")
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-09-17 12:06

you need to follow some steps

step1

initially embed with your initial VC to navigation controller , for e.g

Now select the first controller in Storyboard and click on Editor > Embed in... > Navigation Controller.

enter image description here

step2

Now you have to link the second Controller in Storyboard with your new SecondViewController.swift file.

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

for e.g

enter image description here

step3

Passing a String

Now select the other controller in Storyboard and add this variable right below the SecondViewController class declaration:

 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

step4

on your first VC , inside the button

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

   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

change your 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

 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:

 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

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)
  }
查看更多
登录 后发表回答