//2个界面传值反向
第一个界面
import UIKit
//闭包
typealias TwoViewControllerClosure = (_ text:String) ->Void
class ViewController: UIViewController{
let textlable = UILabel();
let TwoVc = TwoViewController();
override func viewDidLoad() {
super.viewDidLoad()
self.title = "首页";
textlable.frame = CGRect(x:50,y:100,width:self.view.frame.size.width-100,height:30);
textlable.textColor = UIColor.black;
textlable.textAlignment = NSTextAlignment.center;
textlable.backgroundColor = UIColor.red;
textlable.text = "我要这这段话传给另一个界面"
// textlable.frame = (x:100, y:100,witdh:self.view.frame.size.width,height:30);
self.view .addSubview(textlable);
let btn = UIButton();
btn.frame = CGRect(x:50,y:150,width:100,height:30);
btn.setTitle("跳转下一页", for: UIControlState.normal);
btn.setTitleColor(UIColor.blue, for: UIControlState.normal);
btn.addTarget(self, action:#selector(btnOnlick), for: UIControlEvents.touchUpInside);
self.view .addSubview(btn);
//闭包传值
self.TwovcClouse();
}
/界面二闭包传值
func TwovcClouse(){
//闭包
TwoVc.twoVcClouse = {(_ text:String) ->Void in
print("闭包传过来的值为\(text)");
self.textlable.text = text;
}
}
//界面二
import UIKit
//闭包
typealias TwoViewControllerClosure = (_ text:String) ->Void
class TwoViewController: UIViewController {
var string:String = "";
//代理变量
var delegate:TwoMessageDelegate?;
//闭包变量
var twoVcClouse:TwoViewControllerClosure?;
//通知
let NotifMycation = NSNotification.Name(rawValue:"TWoVc");
override func viewDidLoad() {
super.viewDidLoad()
self.title = "界面二";
let textlable = UILabel();
textlable.frame = CGRect(x:50,y:100,width:self.view.frame.size.width-100,height:30);
textlable.textColor = UIColor.black;
textlable.textAlignment = NSTextAlignment.center;
textlable.backgroundColor = UIColor.red;
if string.isEmpty {
print("空")
textlable.text = "字符串为空";
}else{
textlable.text = self.string;
}
self.view .addSubview(textlable);
let btn = UIButton();
btn.frame = CGRect(x:50,y:150,width:100,height:30);
btn.setTitle("返回上一页", for: UIControlState.normal);
btn.setTitleColor(UIColor.blue, for: UIControlState.normal);
btn.addTarget(self, action:#selector(btnOnlick), for: UIControlEvents.touchUpInside);
self.view .addSubview(btn);
}
//传值给上一个界面用闭包和代理分别试试
@objc func btnOnlick(){
//闭包写法
//self.TwoVcClosure();
self.navigationController?.popViewController(animated: true);
//静态返回
//self.dismiss(animated: <#T##Bool#>, completion: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>)
}
func TwoVcClosure() {
if twoVcClouse != nil {
twoVcClouse!("我是用闭包传值的");
}
}