如何以编程方式在不同的视图控制器之间传递字符串(Swift)

How To Pass String Between Diffirent View Controllers Programatically(Swift)

我正在尝试将字符串从 VCOne 中的 IDNumber 传递到 VCTwo 中的 postString。 我尝试了几种不同的方法但没有成功。任何帮助将不胜感激! (我也没有使用 StoryBoards 或 SwiftUI)所有代码都有效,除了两个 VC 之间的传递

ViewControllerOne:

import UIKit

class ViewControllerOne: UIViewController {

    var IDNumber : UITextView = {
        var PNTF = UITextView()
        PNTF.translatesAutoresizingMaskIntoConstraints = false
        PNTF.isUserInteractionEnabled = true
        PNTF.isEditable = true
        PNTF.layer.borderColor = CGColor.init(srgbRed: 0, green: 0, blue: 0, alpha: 1)
        PNTF.layer.borderWidth = CGFloat.init(1)
        PNTF.layer.cornerRadius = CGFloat.init(7.5)
        PNTF.layer.masksToBounds = true
        PNTF.font = UIFont(name: "HelveticaNeue", size: 20)
        PNTF.keyboardType = .asciiCapable
        PNTF.keyboardAppearance = .dark
        return PNTF
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(IDNumber)
        setupLayout()
        SetupNavBar()

        // Do any additional setup after loading the view.
    }
    func SetupNavBar() {
        navigationItem.title = "VC One"
        let titleFont = [NSAttributedString.Key.font : UIFont(name: "HelveticaNeue", size: 20)!]
        navigationController?.navigationBar.titleTextAttributes = titleFont
        navigationController?.navigationBar.barTintColor = .systemBackground
        navigationController?.navigationBar.prefersLargeTitles = false
        let SegueToVCTwo = UIBarButtonItem(image: UIImage(systemName: "checkmark.square"), style: .plain, target: self, action: #selector(Segue))
        self.navigationItem.leftBarButtonItem = SegueToVCTwo
    }
    @objc func Segue() {
        let segue = UINavigationController(rootViewController: ViewControllerTwo())
        segue.modalPresentationStyle = .pageSheet
        self.navigationController?.present(segue, animated: true)
    }
    func setupLayout() {

        IDNumber.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 15).isActive = true
        IDNumber.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 15).isActive = true
        IDNumber.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true
        IDNumber.heightAnchor.constraint(equalToConstant: 15).isActive = true
    }
}

ViewControllerTwo:

import UIKit

class ViewControllerTwo: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        SetupNavBar()


        // Do any additional setup after loading the view.
    }
    func SetupNavBar() {
        navigationItem.title = "VC Two"
        let titleFont = [NSAttributedString.Key.font : UIFont(name: "HelveticaNeue", size: 20)!]
        navigationController?.navigationBar.titleTextAttributes = titleFont
        navigationController?.navigationBar.barTintColor = .systemBackground
        navigationController?.navigationBar.prefersLargeTitles = false
    }
    func QueryChipNumber() {
        let request = NSMutableURLRequest(url: NSURL(string: "https://api.tskfce.com/snapdragon.php")! as URL)
            request.httpMethod = "POST"
            let postString = "ID=\()"
            request.httpBody = postString.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in
                guard error == nil && data != nil else{
                    print("error")
                    return
                }
                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200{
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }
            }
            task.resume()
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

在 class 范围内定义 postString

var postString:String = ""

在 push

之前从 FirstVC 分配第二个 VC postString
@objc func Segue() {
        let vc = ViewControllerTwo()
        vc.postString = IDNumber.text ?? ""
        let segue = UINavigationController(rootViewController: vc)
        segue.modalPresentationStyle = .pageSheet
        self.navigationController?.present(segue, animated: true)
    }

现在您可以在第二个中使用 postString VC

func QueryChipNumber() {
        let request = NSMutableURLRequest(url: NSURL(string: "https://api.tskfce.com/snapdragon.php")! as URL)
            request.httpMethod = "POST"

            request.httpBody = postString.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in
                guard error == nil && data != nil else{
                    print("error")
                    return
                }
                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200{
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }
            }
            task.resume()
    }

你可以这样做:

class ViewControllerOne: UIViewController {

func jumpToVc2() {
        let vc = ViewControllerTwo()
        vc.postString = IDNumber.text ?? ""
        let segue = UINavigationController(rootViewController: vc)
        segue.modalPresentationStyle = .pageSheet
        self.navigationController?.present(segue, animated: true)
}
}

class ViewControllerOne: UIViewController {
var postString = String()
 //you can user poststring anywhere you want
func QueryChipNumber() {
    let request = NSMutableURLRequest(url: NSURL(string: "https://api.tskfce.com/snapdragon.php")! as URL)
        request.httpMethod = "POST"
        request.httpBody = "ID=\(postString)".data(using: String.Encoding.utf8)
        let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in
            guard error == nil && data != nil else{
                print("error")
                return
            }
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200{
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }
        }
        task.resume()
}


}