1. 程式人生 > >通過Appdelegate,來進行反向頁面傳值

通過Appdelegate,來進行反向頁面傳值

//先在Appdelegate裡建立一個變數
//例
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    //建立一個變數
    var zuowen:String = ""

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let nav = UINavigationController(rootViewController: ViewController())
        self.window?.rootViewController=nav
        
        return true
    }
    <---------------分界線---------------->
    //然後在你的主頁面裡開始寫
    //用Appdelegate傳它的變數,zuowen是一個隨意的名字
        let zuowen:AppDelegate = (UIApplication.shared).delegate as! AppDelegate
        //這裡是表格的主Label內容。只是一個賦值的栗子
          cell?.textLabel?.text = zuowen.zuowen

//然後在第二個頁面中寫
	var text = UITextField()
    override func viewDidLoad() {
        super.viewDidLoad()
         self.view.backgroundColor=UIColor.white
         text = UITextField(frame: CGRect(x: 50, y: 100, width: 200, height: 40))
        text.backgroundColor=UIColor.blue
        
        
        self.view.addSubview(text)
        let button = UIButton(frame: CGRect(x: 50, y: 150, width: 40, height: 40))
        button .setTitle("確定", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.addTarget(self, action: #selector(fangfa), for: .touchUpInside)
        button.backgroundColor=UIColor.black
        self.view.addSubview(button)
        
       
        
    }
    //按鈕方法
 @objc func fangfa(){
       //通過Appdelegate的變數賦值
        let zuowen:AppDelegate = UIApplication.shared.delegate as! AppDelegate
        zuowen.zuowen=text.text!
        print("傳值成功")
        //這裡的跳轉方式要和前一個頁面所對應 pop push
        self.navigationController?.popViewController(animated: true)
        
    }