【Xcode/Swift】画面遷移先に値を渡そう

実装

HomeViewController.xib & NextViewController.xib (StoryboardでもOK)

HomeViewController.swift

import UIKit

final class HomeViewController: UIViewController {
    // MARK: - Properties
    @IBOutlet private weak var nameTextField: UITextField!
    @IBOutlet private weak var showNextViewButton: DesignableButton!

    // MARK: - View Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func showNextViewAction(_ sender: Any) {
        let nextViewController = NextViewController(nibName: "NextViewController", bundle: nil)
        nextViewController.modalPresentationStyle = .fullScreen
        guard let userName = nameTextField.text else { return }
        nextViewController.userName = userName
        self.present(nextViewController, animated: true)
    }

}

NextViewController.swift

import UIKit

class NextViewController: UIViewController {
    @IBOutlet private weak var nameLabel: UILabel!
    @IBOutlet private weak var backButton: DesignableButton!

    public var userName: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        nameLabel.text = "Your Name is \(userName)"
    }

    @IBAction func backAction(_ sender: Any) {
        self.dismiss(animated: true)
    }

}

この記事は役に立ちましたか?

はい
いいえ
貴重なフィードバックありがとうございます!