Swift 视图控制器之间的反向传值

ViewController.swift

import UIKit

class ViewController: UIViewController{
    
    // Create a class variable for designation method to visit its attributes.
    let labelOne = UILabel();
    
    // Create a class variable for clourse to visit.
    var mainContent: String = "";
    
    @objc func mainListener(){
        let svc = SecondViewController();
        // Create an optional closure to get the variable.
        svc.closure = {(data: String) in
            self.mainContent = data;
            self.labelOne.text = self.mainContent;
            print(self.mainContent);
        }
        self.present(svc, animated: true, completion: nil);
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
//        let labelOne = UILabel(frame: CGRect(x: 30, y: 120, width: 240, height:30));
        labelOne.frame = CGRect(x: 30, y: 120, width: 240, height:30);
        labelOne.text = "Fuyang Normal Colleage";
        labelOne.textColor = UIColor.purple;
        labelOne.font = UIFont.boldSystemFont(ofSize: 20);
        self.view.addSubview(labelOne);
        
        let butttonOne = UIButton(type: UIButton.ButtonType.system);
        butttonOne.frame = CGRect(x: 200, y:400, width: 100, height: 30);
        butttonOne.setTitle("ButtonOne", for: UIControl.State())
        self.view.addSubview(butttonOne);
        
        butttonOne.addTarget(self, action: #selector(mainListener), for: UIControl.Event.touchUpInside);

    }
    
}

SecondViewController.swift

import UIKit

class SecondViewController: UIViewController {
    
    // Create an optional clourse.
    var closure: ((String) -> Void)?;
    
    @objc func secondListener(){
        // Set the content into clourse.
        self.closure!("Fuyang Normal University");
        self.dismiss(animated: true, completion: nil);
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.orange;
        
        let butttonOne = UIButton(type: UIButton.ButtonType.system);
        butttonOne.frame = CGRect(x: 100, y:300, width: 120, height: 30);
        butttonOne.setTitle("Second", for: UIControl.State())
        self.view.addSubview(butttonOne);
        
        butttonOne.addTarget(self, action: #selector(secondListener), for: UIControl.Event.touchUpInside);

        // Do any additional setup after loading the view.
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值