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

sr4lhrrt  于 2023-05-05  发布在  Swift
关注(0)|答案(2)|浏览(109)

我试图将一个字符串从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
    }
}

视图控制器二:

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.
    }
    */

}
axr492tv

axr492tv1#

你可以这样做:

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

}
zaqlnxep

zaqlnxep2#

在类作用域中定义postString

var postString:String = ""

在推送前从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)
    }

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

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

相关问题